Demon Process

A daemon process, also known as a daemon, is a background process in Linux operating system that runs continuously, performing specific tasks even when no user is logged in. Unlike normal processes, daemons do not have a controlling terminal and they don't respond to signals from the keyboard. Demon Usually do not die or get restarted, waits for requests to arrive and respond to them and frequently spawn other processes to handle these requests.

One of the main characteristics of a daemon process is its ability to run in the background, without any direct user interaction. This allows the daemon to perform tasks without the user being aware of it, making it an important component of Linux operating system. Daemons can perform a variety of tasks, such as managing resources, monitoring system performance, handling requests, or managing background services.

A Linux process works either in foreground or background.

We can run the program in foreground in the terminal as ./a.out

We can run the program in background in the terminal as a.out &

A process running in foreground can interact with the user in front of the terminal. 

To create a daemon process, a programmer must follow specific steps such as

1.Create a separate child process using fork().

2. Make child process In-dependent - setsid()

Process groups are themselves grouped into sessions. Process groups are not permitted to migrate from one session to another, and a process may only create new process groups belonging to the same session as it itself belongs to. Processes are not permitted to join process groups that are not in the same session as they themselves are.

3. Change current Running Directory - chdir()

A daemon process should run in a known directory. If the home directory is a mounted filesystem then it will even create many issues if the filesystem is accidentally un-mounted.

4. Close Inherited Descriptors and Standard I/O Descriptors

A child process inherits default standard I/O descriptors and opened file descriptors from a parent process, this may cause the use of resources un-necessarily.

5. Reset File Creation Mask - umask()

Daemon processes usually runs as super-user, for security reasons they should protect files that they create. Setting user mask will prevent unsecure file priviliges that may occur on file creation
A umask value of 0 means that all permissions are granted by default. For example, if the umask is set to 0, newly created files will have full read, write, and execute permissions for the owner, group, and others.

Ex:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>    //for fork and setsid functions.
#include <sys/types.h>  // for data types such as pid_t.
#include <sys/stat.h>  // for umask function.
#include <syslog.h>  // for logging related functions.
#include <fcntl.h> // For O_RDWR argument 

int main(void)
{
    pid_t pid, sid;
    int fd;

    pid = fork();
    if (pid < 0) {
        exit(EXIT_FAILURE);
    }
    if(pid == 0 && getppid() == 1) {
    // Already demon , since its parent is init, init process pid is 1.
        exit(EXIT_SUCCESS);
    }

    if (pid > 0) {
        exit(EXIT_SUCCESS);
    }

    umask(0);  //The umask function sets the file mode creation mask to 0,
               // so that the process can access all files with the specified permissions.

    sid = setsid(); // The setsid function creates a new session 
                    // and sets the process group ID to the process ID of
                    // the calling process. The session ID is stored in sid.
     
    if (sid < 0) {
         // Condition checks if the call to setsid() failed.
         //  If it failed, it means that the process could not be detached 
         // from its parent process, and the creation of the demon process 
         // was not successful. In this case, 
         // the program exits with an error code.          
         exit(EXIT_FAILURE);
      }
  
      if ((chdir("/")) < 0) {
          exit(EXIT_FAILURE);
      }
      // The chdir function changes the current working directory of
      // the process to the root directory. 
      // This is to ensure that the daemon process will not be affected 
      // by changes in the current working directory. 
      // If the chdir function fails, the process will exit with
      //  failure status.

      fd = open("/dev/null",O_RDWR,0);  //  opens the file "/dev/null".
     
      // dev/null is a special file in Linux, also known as the "null device".
      // When you write data to this file, it is discarded, and when you read
      // from it, you get no data.

      // The open() function returns a file descriptor, which is a number 
      // that represents an open file. The file descriptor is stored in the 
      // variable fd.
      // The O_RDWR argument indicates that the file is being opened for 
      // both reading and writing. The last argument, 0,sets the file 
      // permissions. In this case, it is not necessary, so 0 is passed.
	 
      if(fd!=-1) {
	      dup2(fd,STDIN_FILENO);
		  dup2(fd,STDOUT_FILENO); // Comment this line for easy debugging 
		  dup2(fd,STDERR_FILENO);
	      if(fd>2) {  //  if the file descriptor "fd" is greater than 2 
                      // (which represents the standard input, output and error)
              close(fd);
	      }
	  }  
     
     /*
      dup2(fd, STDIN_FILENO); is a system call that duplicates the file
      descriptor fd into the file descriptor number STDIN_FILENO,
      which is the standard input file descriptor for the process. 
      This is done so that any input that would normally be sent to standard 
      input (e.g. via scanf) will instead be discarded and sent to /dev/null,
      which is a special file in the Unix-like operating system that acts as 
      a black hole. Any data written to this file is discarded and cannot be 
      read back. This is useful when running a daemon process that should not 
      interact with the user, but still wants to discard any input.
     */
  
      openlog("demonprocess", LOG_PID, LOG_DAEMON);
      // The openlog function is used to open the system log for 
      // the daemon process. The first parameter is the identifier string,
      // the second parameter is to include the process ID with each 
      // log message, and the third parameter is to log messages as 
      // a daemon process.
  
      while (1) { //  Infinite loop to run the daemon process continuously.
          syslog(LOG_NOTICE, "demon is running, Kill me if you can");
         //printf("demon is running, Kill me if you can");  // Uncomment this line for easy debugging 
         // fflush(stdout); // Uncomment this line for easy debugging
          sleep(20); // The exit function is used to exit the process with success status.
      }
  
      closelog();
      exit(EXIT_SUCCESS); //The exit function is used to exit the 
                          // process with success status.
  }        

Compile: gcc DemonProcess.c

Run : ./a.out

The output of syslog can be seen by tail -f /var/log/syslog

For easy debugging the do below 2 modifications:

  1. Comment dup2(fd,STDOUT_FILENO); -> so that you can see the print "demon is running, Kill me if you can" for every 30 sec on standard out terminal.
  2. Uncomment printf("demon is running, Kill me if you can"); and fflush(stdout);

Note: This just for debugging purpose, in actual code it should not be commented

How to kill the demon process:

command: kill -9 PidOfDemonProcess (Here -9 means SIGKILL )

kill -15 PidOfDemonProcess (Here -15 means SIGTERM)

or even just kill PidOfDemonProcess also works in some Linux flavors.

How to know the pid of demon process:

  1. Use ps -elf in terminal
  2. pidof processName Ex: pidof a.out
  3. glances -- This is advanced command with advance features.

The kill command sends a signal to the process to terminate it. The signal used for termination is usually the SIGTERM/SIGKILL signal, which is the default signal sent by the kill command.

Some of the common uses cases where demon process is created include:

  1. Resource management: Daemon processes can be used to manage system resources, such as memory, disk space, or network connections. Demon processes are used to allocate resources, such as CPU time, memory, and disk space, among different processes.
  2. Monitoring system performance: Daemons can monitor system performance, including CPU utilization, disk space, and network traffic, and take action based on predefined rules. Demon processes can be used to monitor other processes and alert the system administrator if something goes wrong.
  3. Background services: Daemon processes can run in the background, providing various services to users, such as printing, email, or file transfer.
  4. Handling requests: Daemon processes can handle requests from clients, such as web requests, database queries, or network requests, and respond to them in a timely manner.
  5. System management: Daemon processes can perform various system management tasks, such as starting and stopping services, updating configuration files, or performing backups.
  6. Daemons for system services: Many system services, such as print servers, network servers, or database servers, are implemented as demon processes.
  7. Scheduling tasks: Demon processes are used to schedule tasks, such as periodic backup, log rotation, and database maintenance, in the background.
  8. Network services: Demon processes are used to implement network services, such as web servers, email servers, and FTP servers.


There are two types of demons based on terms of their origin and scope of operation:

The differences between the two include the process that spawns them, the level of access they have to system resources, and the level of control that users have over them.

  1. System level demons System level demons are created and managed by the init process, which is a part of the kernel. Modifying the kernel source code (init process source code )is a complex process that requires deep understanding of the operating system and its components. It's not recommended for inexperienced users or those without a good understanding of the Linux kernel and its internals. Modifying the kernel source code should only be done after careful consideration and testing, as it can have significant impact on the stability and security of the system. In general, it's best to avoid modifying the kernel source code if possible, and instead use other methods, such as creating a user-space daemon process, to accomplish your goal. The init process is typically defined in the file /sbin/init or /lib/systemd/systemd in a Linux system. System level demons are background processes that are started by the operating system's init process during system boot up. These daemons are responsible for providing core system services and performing tasks that are critical to the proper functioning of the operating system. Examples of system level demons include syslogd, klogd, and crond.

2. User level demons are created and managed by user space processes or by the user themselves. User level demons are background processes that are created and managed by user space applications or by the users themselves. These demons run as separate entities from the operating system and are not critical to its functioning. They are often used to perform non-critical tasks such as monitoring the system, data processing, or serving as a background worker. User level demons can be created and managed without the need for recompiling the operating system's kernel. Examples of user level demons: media players, web servers, and other software that runs in the background to provide specific services to the user.

Some common Linux demon processes include:

  1. init: init is the first process that is started when the system boots. It is responsible for initializing the system and starting all the other necessary processes.
  2. syslogd: syslogd is the system log daemon, which is responsible for logging system messages and events.
  3. klogd: klogd is the kernel log daemon, which is responsible for logging kernel messages and events.
  4. crond: crond is the cron daemon, which is responsible for executing scheduled tasks, such as running scripts and executing commands.
  5. SSH demon: SSH demon is the SSH server, which is responsible for providing secure shell access to the system.
  6. httpd (Apache): httpd is the Apache HTTP server, which is responsible for serving web pages and handling HTTP requests.
  7. ntpd: ntpd is the Network Time Protocol daemon, which is responsible for maintaining the system clock and synchronizing it with a network time server.
  8. mysqld (MySQL): mysqld is the MySQL database server, which is responsible for managing and serving databases.
  9. smbd (Samba): smbd is the Samba server, which is responsible for providing file and print services to Windows clients.
  10. named (DNS): named is the Domain Name System (DNS) server, which is responsible for resolving domain names to IP addresses.
  11. gdm (GNOME Display Manager): gdm is the GNOME Display Manager, which is responsible for managing graphical user logins.
  12. cupsd (Common Unix Printing System): cupsd is the Common Unix Printing System daemon, which is responsible for managing printing and managing print jobs.
  13. xinetd (Extended Internet daemon): xinetd is the Extended Internet daemon, which is responsible for managing Internet services, such as Telnet and FTP.
  14. Postfix mail transfer agent: Postfix is a mail transfer agent, which is responsible for delivering email messages to the correct destinations.

Daemon processes are an important part of the Linux operating system, but they should be used with caution and carefully monitored to ensure that they do not consume too many system resources or pose a security risk.

Let me list the advantage and disadvantages.

Advantages of daemon process:

  1. Persistence: Daemon processes are long-running processes that continue to run even after the user who started them logs off.
  2. Resource utilization: Daemon processes use system resources such as memory, disk space, and CPU time, but they do so in the background and do not interfere with the user's work.
  3. Background Services: Daemon processes provide essential background services, such as running a print server, monitoring network traffic, or backing up files.
  4. Improved system performance: Daemon processes can improve system performance by running tasks in the background while the user is performing other tasks.

Disadvantages of daemon process:

  1. Resource utilization: Daemon processes can consume a large amount of system resources, especially if they are running continuously.
  2. Security Risks: Daemon processes can be vulnerable to hacking or other security threats, and they can be used to launch malicious attacks on the system.
  3. Debugging Difficulties: Debugging daemon processes can be difficult, as they run in the background and do not provide feedback to the user.
  4. System crashes: If a daemon process crashes, it can bring down the entire system, making it difficult to recover from the crash.

In conclusion, daemon processes are an important component of Linux operating system, playing a crucial role in managing resources, monitoring system performance, and handling requests. To create a daemon process, a programmer must follow specific steps, such as forking a child process, setting the process group id, and creating a new session.


Thanks for reading till end, If you have any questions or suggestions, please leave a comment.

Anantha Narayanan

Project leader at Lennox India Tech. Private Limited

1y

Hi Amit Nadiger , Thanks for such informative article.. Some of the findings. 1. Title is daemon process 2. Daemons are not just forking from any parent. Then they would be equivalent to background processes run from Linux services. 3. Daemon process is usually forked from init process. 4. Also they can't be controlled / managed by user space unlike normal service bound process.. Just from my understanding guruji. Pls correct me if my understanding in deviating.. Thanks

Like
Reply

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics