Tom
Tom

Reputation: 19302

Why doesn't my daemon terminate when I log out?

I'm reading about Linux process groups and sessions. From this site I see:

When a user logs out of a system, the kernel needs to terminate all the processes the user had running...To simplify this task, processes are organized into sets of sessions. The session's ID is the same as the pid of the process that created the session through the setsid() system call. That process is known as the session leader for that session group. All of that process's descendants are then members of that session unless they specifically remove themselves from it. The setsid() function does not take any arguments and returns the new session ID.

What the article doesn't say is when the OS decides to terminate a user's sessions. My initial assumption was that when someone logs into a TTY, the TTY is the session leader and all processes invoked in that session belong to it unless they call setsid(). However, this is clearly wrong as verified by the simplest of examples. Consider this "daemon"... (I know it's not a real daemon, but it does fork)...

#include 
#include 
#include 
#include 

int main(void) {

  pid_t pid = fork();

  if(pid < 0) {
    perror("fork");
    exit(EXIT_FAILURE);
  }

  if(pid == 0) {
    FILE * heartbeat_file = fopen("daemon.out", "w");
    int hb = 0;
    while(1) {
      fprintf(heartbeat_file, "%d\n", hb);
      fflush(heartbeat_file);
      hb++;
      sleep(1);
    }
  } 
  exit(EXIT_SUCCESS);
}

From the code, we see that the child continually writes to a file, and the parent exits. Note that I'm never calling setsid().

If I log in, run the daemon, and then log out, and then log in, the daemon is still running! I can remove the call to fork() and as expected, the process terminates when I log out. Can anyone explain why fork causes the app not to exit when I log out?

Upvotes: 1

Views: 583

Answers (1)

KrahnacK
KrahnacK

Reputation: 313

When you fork while letting the parent exit, you create an orphan process (http://en.wikipedia.org/wiki/Orphan_process). Such orphans are re-parented to the init process. I would assume from what you observe that the re-parenting modifies the session's ID.

A straightforward way to test this assumption would be for the parent to wait on the child (sorry i'm not on my linux box at the moment, and can't do it).

Upvotes: 1

Related Questions