Issue
Let's say we have:
background() {
: # Loop to do something very important
}
background &
# main process code here
Could the "background" process detect when the "main" process is terminated?
Solution
$$
refers to the main shell's PID (if you need to get the PID of the current subshell, that's $BASHPID
instead).
You can use kill -0
as a portable way (in that it doesn't depend on procfs or other linuxisms, not that in the sense of guaranteed availability outside bash) to test if a process is still running. Thus:
if kill -0 "$$"; then
echo "Main process is still running"
else
echo "Main process has terminated"
fi
Answered By - Charles Duffy Answer Checked By - Terry (WPSolving Volunteer)