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:
Note: This just for debugging purpose, in actual code it should not be commented
Recommended by LinkedIn
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:
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:
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.
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:
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:
Disadvantages of daemon process:
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.
Project leader at Lennox India Tech. Private Limited
1yHi 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