1

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!

AndyW
  • 357
  • 3
  • 15
  • Do you mean to say kill all the background processes when the parent script that started exits? – Inian Nov 23 '16 at 17:22
  • Yes! How can I do that? Thanks. – AndyW Nov 23 '16 at 17:25
  • I guess you will be needing `trap` command on parent process exit, but am not sure how to use it though. – Inian Nov 23 '16 at 17:25
  • Yes, I found this http://stackoverflow.com/questions/360201/how-do-i-kill-background-processes-jobs-when-my-shell-script-exits but I'm also a bit unsure how to use it – AndyW Nov 23 '16 at 17:26
  • Exactly what I meant! I think you can try using that command on the parent script and let us know. – Inian Nov 23 '16 at 17:28
  • Yes, the problem is I'm confused as to where in my code I should put that and how to implement it. I'm reading more now... – AndyW Nov 23 '16 at 17:36
  • Got it to work I believe. Thanks so much for your help! – AndyW Nov 23 '16 at 17:38
  • Post what you have tried and worked and accept it, so that people can find it useful in the future. – Inian Nov 23 '16 at 17:39

1 Answers1

-1

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
AndyW
  • 357
  • 3
  • 15
  • 4
    Add a bit more context on the problem you faced and explain how this command solved it! – Inian Nov 23 '16 at 17:48
  • Looks like the source for this answer (which should have been cited) is this: https://stackoverflow.com/a/2173421/1941654 (which also refers to https://stackoverflow.com/a/28333938/1941654). `trap - SIGTERM` prevents segfaults due to infinite recursion on SIGTERM. `kill -- -$$` kills all processes in the process group. – Mike Hill Nov 02 '18 at 19:06