Home > Net >  Bash: could a background process detect when the main process is ended?
Bash: could a background process detect when the main process is ended?

Time:01-12

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?

CodePudding user response:

$$ 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
  •  Tags:  
  • Related