In my web development workflow, I have two processes:
- watching my folder for changes
- previewing my site in the browser
I want to be able to run them and then later stop them both at the same time. I’ve seen everyone suggesting using the ampersand operator:
process_1 & process_2
But pressing Ctrl + C only stops the second one. I have to kill the first one manually. What am I missing in this approach?
You can have the foreground script explicitly kill the subprocesses in response to SIGINT:
There is a race condition in this example: if you send
SIGINTto the parent beforepid1is assigned,killwill emit a warning message and neither child will be terminated. If you sendSIGINTbeforepid2is assigned, only the process runningcmd1will be sent the signal. In either case, the parent will continue running and a secondSIGINTcan be sent. Some versions ofkillallow you to avoid this race condition by sending a signal to the process group usingkill -$$, but not all versions ofkillsupport that usage. (Note that if either child process does not terminate in response to the signal, the parent will not exit but continue waiting.)