3 ms·
I have solved this problem, except for grandchildren processes. (Use some non-portable construct if you must.) This is what I did: I have one thread whose sole
by gavinhoward 3y ago
I have solved this problem, except for grandchildren processes. (Use some non-portable construct if you must.)
This is what I did: I have one thread whose sole purpose is to wait on children. It's activated by a semaphore. But it will wait and then send a message through a pipe to the thread that started that child when the child exits. (As a side benefit, the launching thread can then use poll() or other fd waiting.)
The killer is killing children; I found that it is best to kill all children that haven't been waited on when killing is necessary. The problem is that child exit messages can block the pipe, so you need to take them out, but they may arrive in a different order than you expect. If you're just killing all children launched by that thread, no problem, just read and ignore every time you kill a child.
There are a lot of details (that code has the single longest code comment I've written in my life), but most of them are in that classic "Gotchas" document matklad references.
- PeterWhittaker 3y agoBut as the original article mentions, what about the case where your parent process is killed uncatchably, e.g., with kill -9? Your children may persist, because the parent was not afforded an opportunity to kill them.
- gavinhoward 3y agoNotice that I said I didn't solve the grandchild problem.
- mksybr 3y agoDoesn't kill -9 impact the ability to kill even children, due to not being given time to clean up?
- gavinhoward 3y agoYes, but at that point, it is the problem of the grandparent, which isn't dead.
- catern 3y agoWhen a process does, its children are reparented to init, not to its parent. So the grandparent can do nothing.
- gavinhoward 3y agoYes, I know. But leaking grandchildren is still a problem for the grandparent.
- deleted 3y ago[deleted]
- PeterWhittaker 3y agoI’m not referring to grandchildren: if you have parent P with children C1 and C2 and P receives -9, P dies and C1 and C2 persist.
- gavinhoward 3y agoYes, but if a process gets a SIGKILL, the user is explicitly saying that they don't want that process to do anything else. Otherwise, they would send a SIGTERM. So a SIGKILL is really the user passing the responsibility of the children onto some other process.
- catern 3y agoI think you may have misunderstood the problem that this article is solving. You've implemented something which kills all your child processes when you exit cleanly, but which leaks child processes if you exit uncleanly. This is, frankly, easy to do, and not interesting. It's not a "problem". The article is solving the problem of: how do I make sure my child processes die even if I exit uncleanly? That's an actual hard problem to solve.