[flang-commits] [flang] [flang] use setsid to assign the child to prevent zombie as it will be clean up by init process (PR #77944)

Yi Wu via flang-commits flang-commits at lists.llvm.org
Fri Jan 12 08:55:07 PST 2024


https://github.com/yi-wu-arm created https://github.com/llvm/llvm-project/pull/77944

When using `setsid()` in a child process created by `fork()`, a new session is created, and the child becomes a session leader. If the parent process terminates before the child, the child becomes an orphan and is adopted by the `init` process. The `init` process will eventually clean up the child process once it exits. 

However, killing the parent does not automatically kill the child; the child will continue running until it exits. 
Proper cleanup involves waiting for the child process to exit using `wait()` or `waitpid()` in the parent process to avoid zombie processes, but this approach is not valid for `EXECUTE_COMMAND_LINE` with async mode.


>From b51f293d57a1ae96fab5d3b2a529186a78643c8c Mon Sep 17 00:00:00 2001
From: Yi Wu <yi.wu2 at arm.com>
Date: Fri, 12 Jan 2024 16:44:21 +0000
Subject: [PATCH] use setsid to assign the child to prevent zombie as it will
 be clean up by init process

---
 flang/runtime/execute.cpp | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/flang/runtime/execute.cpp b/flang/runtime/execute.cpp
index 48773ae8114b0b..1bd5bb81ec8461 100644
--- a/flang/runtime/execute.cpp
+++ b/flang/runtime/execute.cpp
@@ -180,8 +180,6 @@ void RTNAME(ExecuteCommandLine)(const Descriptor &command, bool wait,
     }
     FreeMemory((void *)wcmd);
 #else
-    // terminated children do not become zombies
-    signal(SIGCHLD, SIG_IGN);
     pid_t pid{fork()};
     if (pid < 0) {
       if (!cmdstat) {
@@ -191,6 +189,18 @@ void RTNAME(ExecuteCommandLine)(const Descriptor &command, bool wait,
         CheckAndCopyCharsToDescriptor(cmdmsg, "Fork failed");
       }
     } else if (pid == 0) {
+      if (setsid() == -1) {
+        if (!cmdstat) {
+          terminator.Crash(
+              "setsid() failed with errno: %d, asynchronous process initiation failed.",
+              errno);
+        } else {
+          StoreIntToDescriptor(cmdstat, ASYNC_NO_SUPPORT_ERR, terminator);
+          CheckAndCopyCharsToDescriptor(
+              cmdmsg, "setsid() failed, asynchronous process initiation failed.");
+        }
+        exit(EXIT_FAILURE);
+      }
       int status{std::system(newCmd)};
       TerminationCheck(status, cmdstat, cmdmsg, terminator);
       exit(status);



More information about the flang-commits mailing list