Search code examples
linuxbashshellprocesskill

Fork child process to die when parent exits? (bash)


I'm working with parallel processing and rather than dealing with cvars and locks I've found it's much easier to run a few commands in a shell script in sequence to avoid race conditions in one place. The new problem is that one of these commands calls another program, which the OS has decided to put into a new process. I need to kill this process from the parent program, but the parent program only knows the pid of the parent (shell script), so this process keeps executing on its own.

Is there a way in bash to set a subprocess to die when the parent dies? I've tried to figure out how to execute it as a daemon because I read daemons exit when the parent dies, but it's tricky and I can't quite get it right. Thanks!


Solution

  • Found the problem, and this fixed it (except for some pesky messages that somehow cannot be redirected to /dev/null).

    trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT