Skip to content

Instantly share code, notes, and snippets.

@bahamas10
Created November 28, 2022 19:15
Show Gist options
  • Save bahamas10/fa380b99cdbb8b3ae0ece050d01cc3cd to your computer and use it in GitHub Desktop.
Save bahamas10/fa380b99cdbb8b3ae0ece050d01cc3cd to your computer and use it in GitHub Desktop.
bash background
$ ./bash-background
forked sleep in the background as pid 42335
program is running
waiting for pid 42335...
sleep exited with code 0
program has exited
#!/usr/bin/env bash
# fork sleep in the background
sleep 3 &
pid=$!
echo "forked sleep in the background as pid $pid"
# check if program running (should be running)
if kill -0 "$pid" 2>/dev/null; then
echo "program is running"
else
echo "program has exited"
fi
# wait for sleep to finish and get its exit code
echo "waiting for pid $pid..."
wait "$pid"
code=$?
echo "sleep exited with code $code"
# check if program running (should NOT be running)
if kill -0 "$pid" 2>/dev/null; then
echo "program is running"
else
echo "program has exited"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment