core: reduce the number of stalled PIDs from the watched processes list when possible

Some PIDs can remain in the watched list even though their processes have
exited since a long time. It can easily happen if the main process of a forking
service manages to spawn a child before the control process exits for example.

However when a pid is about to be mapped to a unit by calling unit_watch_pid(),
the caller usually knows if the pid should belong to this unit exclusively: if
we just forked() off a child, then we can be sure that its PID is otherwise
unused. In this case we take this opportunity to remove any stalled PIDs from
the watched process list.

If we learnt about a PID in any other form (for example via PID file, via
searching, MAINPID= and so on), then we can't assume anything.
This commit is contained in:
Franck Bui
2019-03-20 10:51:49 +01:00
parent 4d05154600
commit f75f613d25
11 changed files with 43 additions and 28 deletions
+7 -1
View File
@@ -2525,7 +2525,7 @@ void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, UnitNotifyFlag
unit_add_to_gc_queue(u);
}
int unit_watch_pid(Unit *u, pid_t pid) {
int unit_watch_pid(Unit *u, pid_t pid, bool exclusive) {
int r;
assert(u);
@@ -2533,6 +2533,12 @@ int unit_watch_pid(Unit *u, pid_t pid) {
/* Watch a specific PID */
/* Caller might be sure that this PID belongs to this unit only. Let's take this
* opportunity to remove any stalled references to this PID as they can be created
* easily (when watching a process which is not our direct child). */
if (exclusive)
manager_unwatch_pid(u->manager, pid);
r = set_ensure_allocated(&u->pids, NULL);
if (r < 0)
return r;