4

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?

  • 1
    Are you on Linux? If so, you're looking for control groups. (Or just let systemd do it for you.) – derobert Aug 31 '16 at 21:18
  • @derobert I've actually already thought about that. However, cgroups by themselves require root. Indeed, I can ask systemd to create transient services, but this requires fiddling with systemd dbus API (which is far more complex than setpgrp call), and also introduces dependency on systemd, which is not everywhere. Anyway, finding the best process control mechanism would be a topic of another question that I might ask later, once I weigh all available options. – WGH Aug 31 '16 at 21:49
2

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.

| improve this answer | |
  • By "accidentally daemonize" I mostly meant "double fork-parent exit" scenario, not proper daemonizing. Still good to remember that establishing new process group is important part of daemonizing. – WGH Aug 31 '16 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.