Writing data to stderr makes the program to exit after the program becomes a daemon Writing data to stderr makes the program to exit after the program becomes a daemon unix unix

Writing data to stderr makes the program to exit after the program becomes a daemon


If you run this command from a shell, you're probably seeing a new shell prompt between output 4 and output 5 (this would be more noticeable if there were sleeps in between the output lines).

That's because the daemon() system call causes the program to split into two independent processes. This is called a "fork", and can be controlled a little more closely using the fork() system call. After the fork, both processes keep pointers to the open file descriptors: stdin, stdout and stderr. According to "man 3 daemon", the parent process calls exit() after the fork.

When you call your executable from SSH, the SSH session will run one process. It forks off a child, and the main process exits. SSH sees that the command you issued has finished, and so it closes the SSH connection. That closes stdout and stderr. Unfortunately, your child process still has some work to do, but it can't write to the shared stderr because that file descriptor has been closed. If you printed some more debug info, like the return values from the printf() and fprintf() calls, you'd see that it was not able to write to the closed file descriptors.

If, instead of printing to stderr, you printed to a log file (which most daemons do), then you'll see that the child process would continue to run in the background and write as you expected.

If you had chosen to use fork() instead of daemon(), you could have the parent wait until the child finishes. You would do this with pid_t waitpid(pid_t pid, int *stat_loc, int options);.

You might also want to take a look at signals that are sent between the parent and child. When a child process dies, it will send SIGCHILD to the parent. If you'd like the reverse notification, you can set one up (on Linux only) using prctl(PR_SET_PDEATHSIG, SIGHUP);, so that the parent sends a SIGHUP to the child.