Skip to content

Instantly share code, notes, and snippets.

@akutz
Created March 26, 2015 20:56
Show Gist options
  • Save akutz/66c1ab27f0d26ff2e33a to your computer and use it in GitHub Desktop.
Save akutz/66c1ab27f0d26ff2e33a to your computer and use it in GitHub Desktop.
A script for running Chrome headless with Xvfb that properly kills child processes
#!/bin/sh
# The path to the chrome binary
CHROME_BINARY=/opt/google/chrome/chrome
# As long as this is set to 1 the script will
# block at the end
RUNNING=1
get_chrome_binary_pid ()
{
local child_pids=$(ps -o pid= --ppid "$1")
for pid in $child_pids
do
ps -p $pid -o cmd= | grep -q $CHROME_BINARY 2> /dev/null
if [ "$?" -eq "0" ]; then
echo $pid
else
get_chrome_binary_pid "$pid"
fi
done
}
function exit_wrapper()
{
# kill the chrome binary
kill $(get_chrome_binary_pid $$)
# kill myself
RUNNING=0
}
# Handle any incoming signals
trap "exit_wrapper" SIGHUP SIGINT SIGTERM
# Run Chrome headless
/usr/bin/xvfb-run /usr/bin/google-chrome $@ &
xvfb_pid=$!
# Wait for the signal to exit
while [ "$RUNNING" -eq "1" ]
do
sleep 1
done
wait $xvfb_pid
xvfb_exit_code=$?
echo chrome exit code=$xvfb_exit_code
exit $xvfb_exit_code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment