Skip to content

Instantly share code, notes, and snippets.

@polter-rnd
Created August 11, 2023 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polter-rnd/54103c2b1ea4fb7d9d6e976b28df0de6 to your computer and use it in GitHub Desktop.
Save polter-rnd/54103c2b1ea4fb7d9d6e976b28df0de6 to your computer and use it in GitHub Desktop.
Run app with NVIDIA PRIME using Bumblebee, e.g. ./prime-offload.sh xonotic
#!/bin/bash
NVIDIA_DEV=/dev/nvidia0
BUMBLEBEE_SOCKET=/var/run/bumblebee.socket
function init {
set -e
# Create named pipes for talking with bumblebee
local input output
input=$(mktemp -u)
mkfifo -m 600 "$input"
output=$(mktemp -u)
mkfifo -m 600 "$output"
# Run netcat with our pipes instead of stdin/stdout
# It will run in background and stop together with us
nc -U $BUMBLEBEE_SOCKET <"$input" >"$output" &
exec 4>"$input"
exec 5<"$output"
# Tell bumblebee to power on the card
printf "C NoX\0" >&4
local response
read -u 5 -r response
# Check the response
local c="${response:0:1}"
if [ "$c" != "Y" ]; then
if [ -n "$response" ]; then
echo "Bumblebee daemon reported: $response"
else
echo "Failure contacting Bumblebee daemon"
fi
exit 1
fi
# Remove pipe
rm "$input" "$output"
# Wait until modules are initialized
sleep 0.1
}
function show_blockers {
set -e
BLOCKERS=$(lsof -Fc $NVIDIA_DEV 2>/dev/null)
trap 'kill $(grep ^p <<< $BLOCKERS | cut -c2- | tr "\n" " ") 2>/dev/null' INT
echo "$NVIDIA_DEV is in use by the following processes:"
sed -z 's/p\(\S\+\)\sc\(\S\+\)\s/ \1 (\2)\n/g' <<< "$BLOCKERS"
echo "Waiting for them, or press Ctrl+C to kill"
}
function finish {
set -e
# If finish() has already been called, just return
[ -z "$FINISHED" ] || return
FINISHED=1
# Cleanup signal handler
trap '' INT QUIT TERM
# If there are another running apps, exit
if [ "$(netstat -x | grep -cP "^unix\s+3\s.*$BUMBLEBEE_SOCKET$")" -gt 1 ]; then
exit 0
fi
trap "echo; show_blockers" INT
while [ -n "$(lsof -Fc $NVIDIA_DEV 2>/dev/null)" ]; do
sleep 1
done || :
}
init
# Handle signals
trap finish INT QUIT TERM
# Run the program on NVIDIA card
env __NV_PRIME_RENDER_OFFLOAD=1 \
__GLX_VENDOR_LIBRARY_NAME=nvidia \
__VK_LAYER_NV_optimus=NVIDIA_only \
__GL_SYNC_TO_VBLANK=0 "$@" || :
finish
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment