When process groups are usually created

process-groupsprocess-management

I have a program that spawns many instances of other programs. I want to have a clean way to kill them after timeout, even if they spawn subprocesses, sometimes accidentally daemonize, etc.

Right now I use process group approach: each instance is run in its own process group, and I signal the entire group when I want to kill it. And it seems to work fine so far.

However, it's very easy to create a new process group and thus escape from my control. Those programs are not inherently malicious (so they won't try to do this on purpose), but can be very sloppily written. They could be Python scripts, ugly shell scripts, things like that.

So my question is, when exactly process groups are usually created? According to my observations, interactive shells create them, but non-interactive don't. For instance, are they any kind of advanced shell constructs that tend to create new process groups even in non-interactive scripts?

Best Answer

Well, "sometimes accidentally daemonize" would be a problem—part of daemonizing is to disassociate from the process group. See, e.g., Daemonize's page or a Unix Programming FAQ.

Other than that, the one I've come across[*] is script, which sometimes you have to use to capture a command's output (e.g., because it behaves differently when attached to a terminal vs. a pipe). script calls setsid, which also starts a process group.

It's also possible to turn on job control inside a script, which'd probably also do it. Not sure how common that is, though.

[*] I personally have a script I use frequently that runs mpv inside a script, and parses the output.

Related Question