init: Fix a race condition in KillProcessGroup()
Multiple tests in CtsInitTestCases, e.g. RebootTest#StopServicesSIGKILL,
can trigger the following race condition:
* A service is started. This involves calling fork() and also to call
RunService() in the child process. RunService() calls setpgid().
* Service::Stop() is called and calls KillProcessGroup().
KillProcessGroup() calls kill(-pgid, SIGKILL) before the child process
has called setpgid(). pgid is the process ID of the child process. The
kill() call fails because setpgid() has not yet been called.
Fix this race condition by adding a setpgid() call in the parent process
and by waiting from the parent until the child has called setsid() if a
console is attached.
Bug: 213617178
Change-Id: Ieb9e6908df725447e3695ed66bb8bd30e4e38aa9
Signed-off-by: Bart Van Assche <bvanassche@google.com>
diff --git a/init/service.h b/init/service.h
index e7211ec..54bf638 100644
--- a/init/service.h
+++ b/init/service.h
@@ -151,11 +151,12 @@
void NotifyStateChange(const std::string& new_state) const;
void StopOrReset(int how);
void KillProcessGroup(int signal, bool report_oneshot = false);
- void SetProcessAttributesAndCaps();
+ void SetProcessAttributesAndCaps(InterprocessFifo setsid_finished);
void ResetFlagsForStart();
Result<void> CheckConsole();
void ConfigureMemcg();
- void RunService(const std::vector<Descriptor>& descriptors, InterprocessFifo cgroups_activated);
+ void RunService(const std::vector<Descriptor>& descriptors, InterprocessFifo cgroups_activated,
+ InterprocessFifo setsid_finished);
void SetMountNamespace();
static unsigned long next_start_order_;
static bool is_exec_service_running_;