Daemon Process

(Source)

A daemon process in Linux / Unix is a program that runs in the background. Daemons are processes that are often started when the system is bootstrapped and terminate only when the system is shut down. Because they don’t have a controlling terminal, they run in the background. UNIX systems have numerous daemons that perform day-to-day activities.

Few examples of daemon processes -

Execute the  command to get the list of daemon processes running on your system.

Execute the ps -axj command to get the list of daemon processes running on your system.

Few points to note about daemon processes -

Creating a daemon process

  1. Call fork and have the parent exit.
  2. Call setsid to create a new session. Calling setsid make the process -
  3. Change the current working directory to the root directory using chdir.
  4. Call umask to set the file mode creation mask to a known value, usually $0$.

Sample Program & Output

// Imports for `setsid`, `fork`, `chdir`, `sleep`, `getpid`
#include <sys/types.h>
#include <unistd.h> 
// Additional import for `umask`
#include<sys/stat.h>
// Import for `printf`
#include<stdio.h>

void main() {
    pid_t child;

    child = fork();

    if(!child) { // Child enters this branch
        setsid();
        chdir("/");
        umask(0);
        while(1) { // An infinite loop for printing
            sleep(2); // To give a 2s gap between print statements of each iteration
            printf("PID: %d\n", getpid());
            printf("Daemon process is running...\n");
        }
    } else { // Parent enters this branch
        _exit(0);
    }
}

Execution of the above program.

Execution of the above program.

<aside> 💡 Read about cron and Cron Jobs here.

</aside>


Resource Sharing & Priority Inversion

(Source)

In a multiprocessing environment, often many processes are in need to communicate with each other and share some of the resources. A shared resource can be anything that must be used by two or more tasks in a mutually exclusive fashion. The shared resources must also be synchronized from the concurrent access by many processes. Unfortunately, the need to share resources between tasks operating in a preemptive multitasking environment can create conflicts. Two of the most common problems are deadlock and priority inversion, both of which can result in application failure.

Priority Inversion