Issue creating a daemon process on RHEL 8.3

Latest response

Would really appreciate if someone could help me out with a problem I'm having creating a daemon process on RHEL 8.3.

Here's a simple piece of C code to show my issue (apologies for the formatting) :

int main()
{
pid_t pid;
pid = fork();
if (pid == 0)
{
setsid();
setpgid(0,0);
sleep(30);
exit(0);
}
exit(0);
}

It just forks a process that sleeps for 30 seconds - I want this to detach and run in its own process group.

When I run on RHEL 7 I get the following process entry :

ps -ef
root 16918 1 0 19:53 ? 00:00:00 ./myprogram

As you can cee the PPID is correctly set to 1, which is what I want.

If I compile and run the exact same code on RHEL 8.3 I get the following process entry:

ps -ef
root 6432 4845 0 20:08 ? 00:00:00 ./myprogram

As you can see the PPID is not set to 1, but is still part of the session where the program was run from. This means that when the parent exits, e.g. I log off, the daemon process will be killed.

** Q : does anyone know what changed with 8.3 and have any ideas of the code change I need to make to accommodate? **

Many thanks in advance for any advice.

Responses

Hi Andrew,

I quickly tested your code on one RHEL 7.9 and one RHEL 8.4 servers. They behaved identically: PPID was set to 1 and the process died after 30 seconds.

It was a long time since I was developing code, but just as a quick check I did a test on RHEL 8.4.

Note that there are two methods to create a daemonized process:

  1. BSD-style, with daemon(3) function, provided by GNU C library. Note that some caveats apply.

  2. More reliable and robust double fork(2) and setsid(2) functions.

Here is an example of the first method that worked on RHEL 8.4:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]) {

    if (daemon(0, 0) == -1)
        perror("daemon");

    while (1) {
        getpid();
    }

    exit(EXIT_SUCCESS);
}

Regards,

Dusan Baljevic (amateur radio VK2COT)