Search code examples
clinuxdaemon

Running a Linux Daemon vs An infinite loop in the background


I have this code to make a Daemon in C:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

void main() {
  FILE *fp= NULL;
  pid_t process_id = 0;
  pid_t sid = 0;
  // Create child process
  process_id = fork();
  // Indication of fork() failure
  if (process_id < 0)
  {
    printf("fork failed!\n");
    // Return failure in exit status
    exit(1);
  }
  // PARENT PROCESS. Need to kill it.
  if (process_id > 0)
  {
    printf("process_id of child process %d \n", process_id);
    // return success in exit status
    exit(0);
  }
  //unmask the file mode
  umask(0);
  //set new session
  sid = setsid();
  if(sid < 0)
  {
    // Return failure
    exit(1);
  }
  // Change the current working directory to root.
  chdir("/");
  // Close stdin. stdout and stderr
  close(STDIN_FILENO);
  close(STDOUT_FILENO);
  close(STDERR_FILENO);

  while (1)
  {
    // Do your thing
    usleep(2000);
  }
}

I can compile and run this as ./exampleOne and this will run as a daemon in the background forever.

Now reversely, what if I had the following example:

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

void main() {
  while (1)
  {

    // do your thing
    usleep(2000);
  }
}

And then ran it as ./exampleTwo &. This will also now run in the background as an infinite loop.

So what's the difference? The second one is so much simpler.


Solution

  • One simple advantage of the fork/daemon approach is that the programmer decides where the fork will occur which allows the programmer to to provide a guarantee that when one returns to the shell with no errors, the daemon is up and running.

    Running in the background returns to the shell immediately so you daemon may still be in the initialization phase and connection to it may well fail for a while.