This is an automated email from the ASF dual-hosted git repository.

acassis pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit 949daa1f6d8a06409e9e497f0ea2f11677b3b32c
Author: Marco Casaroli <[email protected]>
AuthorDate: Mon Nov 2 16:59:14 2026 +0100

    libs/libc/unistd: Fork in daemon() when fork() is available.
    
    daemon() did not fork: it was written for builds without processes
    and only "pretended" that it forked.  With CONFIG_ARCH_HAVE_FORK (a
    kernel build with address environments) the process that calls
    daemon() stays the child of its parent.  A shell that starts a daemon
    then waits for it: "sshd && sleep 2" did not return until the daemon
    ended.
    
    With CONFIG_ARCH_HAVE_FORK, daemon() now forks as glibc and the BSDs
    do: the parent calls _exit(0), and the child calls setsid(), then does
    the chdir() and the redirection as before.  Without fork() nothing
    changes.
    
    Assisted-by: Claude Code:claude-opus-5-5
    Signed-off-by: Marco Casaroli <[email protected]>
---
 libs/libc/unistd/lib_daemon.c | 28 +++++++++++++++++++++-------
 1 file changed, 21 insertions(+), 7 deletions(-)

diff --git a/libs/libc/unistd/lib_daemon.c b/libs/libc/unistd/lib_daemon.c
index ec33c3d1795..ff2c8c00702 100644
--- a/libs/libc/unistd/lib_daemon.c
+++ b/libs/libc/unistd/lib_daemon.c
@@ -76,13 +76,9 @@
  *           exit(0);
  *       }
  *
- *    This implementation begins essentially 'pretending' that we forked
- *    and that the fork was successful and that we are the child of the
- *    fork.
- *
- *    REVISIT:  Ideally we should remove the parent information from the
- *    the new daemon's group data structure.  That would have a similar
- *    effect to the above fork() operation.
+ *    With CONFIG_ARCH_HAVE_FORK, daemon() forks as above and the child
+ *    calls setsid().  Without fork(), this implementation 'pretends' that
+ *    we forked and that we are the child of the fork.
  *
  * Input Parameters:
  *   nochdir - If nochdir is zero, daemon() changes the process's current
@@ -100,6 +96,24 @@
 
 int daemon(int nochdir, int noclose)
 {
+#ifdef CONFIG_ARCH_HAVE_FORK
+  pid_t pid = fork();
+
+  if (pid < 0)
+    {
+      return -1;  /* fork() will set the errno variable */
+    }
+
+  if (pid > 0)
+    {
+      _exit(0);
+    }
+
+  /* The child: a new session, without a controlling terminal */
+
+  setsid();
+#endif
+
 #ifndef CONFIG_DISABLE_ENVIRON
   if (nochdir == 0)
     {

Reply via email to