How to Create a Linux Daemon?

We independently review everything we recommend. When you buy through our links, we may earn a commission.

How to Create Linux Daemon

Daemons are processes that operate invisibly in the background of your computer without requiring any user interaction. On Linux, you may write your own daemons by following these instructions.

The term “daemon” refers to any process that operates independently from the user and instead performs its duties in the background. In most cases, they begin operating as soon as the system boots up and continue doing so constantly until the system is shut down. The only thing that sets these processes from from regular ones is the fact that they do not in any manner broadcast messages to the console or the screen.

On a computer running Linux, a daemon can be created in the following manner:

An Overview of the Creation of Daemons

A great number of daemons are now active on the system, and some instances of well-known daemons are as follows:

  • crond is a program that ensures instructions are executed at the given time.
  • sshd is a daemon that enables users on faraway computers to log into the local network.
  • httpd is a server that serves web pages.
  • nfsd is an acronym that stands for network file sharing protocol.

In addition, the names of daemon processes often terminate with the letter d, but this is not an absolute need.

The steps below must be carried out in order for a process to function as a daemon:

  • Before a process may become a daemon, it is essential for initial operations to be completed. These first activities may include reading configuration files or acquiring the required system resources. In this method, the system will be able to notify the user of any problems that it has received, and the procedure will be ended with the appropriate error code.
  • It is decided to make init the parent process of a new process that will be operating in the background. In order to accomplish this goal, the init process is first used to create a child process, which is then followed by the termination of the parent process using the exit command.
  • After executing the setsid method to start a new session, the process should then detach from the terminal so that the new session may begin.
  • The child process closes all open file descriptors that were inherited from the parent process.
  • All error messages, as well as the standard input and output, are diverted to the /dev/null device.
  • It is necessary for the process’ working directory to be changed.

What exactly are these Daemon Sessions?

Users are able to launch a wide variety of apps using the shell software once they have successfully logged into the system through a terminal. When the user logs out of the system, these processes ought to be terminated. These sessions and processes are organized into their respective categories by the operating system.

Process groups are a part of each and every session. The following is one way to characterize this predicament:

The terminal at which the processes transmit their outputs and receive the inputs necessary to carry out those operations is referred to as the controlling terminal. One session can be controlled by a controlling terminal at a time, but not more than one.

Identification (ID) numbers are assigned to both a session and the process groups that are contained inside it. These identification numbers also serve as the process identification numbers (PID) of the leaders of the session and process groups. The group membership of a child process is the same as that of its parent process. When there is communication between many processes and the pipe mechanism, the first process that initiates the communication becomes the leader of the process group.

Linux Daemon Process Creation

In this section, you will learn how to develop a daemon function on your own. You are going to give this new function the name _daemon when you make it. You may get started by giving the application code that will operate as a daemon the name test.c. The code with which you will generate the daemon function can be given the name daemon.c.

//test.c
#include <stdio.h>
int _daemon(int, int);
int main()
{
getchar();
_daemon(0, 0);
getchar();
return 0;
}

//daemon.c
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fs.h>
#include <linux/limits.h>
int _daemon(int nochdir, int noclose) {
pid_t pid;
pid = fork(); // Fork off the parent process
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
return 0;
}

It is necessary to have a background process with the init process as its parent in order to construct a daemon. In the code shown above, _daemon first initiates the creation of a child process and then terminates the operation of the parent process. In this scenario, your new process will become a subprocess of init, and it will keep operating in the background even after it has been started.

Compile the program using the following command, and then check the state of the process both before and after using _deamon:

gcc -o test test.c daemon.c

Start the application, and then, without pressing any additional keys, navigate to a separate terminal:

./test

As may be seen, the following is a rundown of the values associated with your process. To obtain information on processes, you will need to issue the ps command at this point. In this particular instance, the _daemon function has not been invoked at this time.

ps -C test -o “pid ppid pgid sid tty stat command”
# Output
PID PPID PGID SID TT STAT COMMAND
10296 5119 10296 5117 pts/2 S+ ./test

When you examine the STAT field, you will notice that your process is now active, but it is awaiting the occurrence of an off-schedule event that will trigger it to begin operating in the background.

AbbreviationMeaning
SWaiting asleep for an event to happen
TApplication stopped
sSession leader
+The application is running in the foreground

You can see that the shell, as was to be expected, is serving as the parent process of your application.

ps -jp 5119
# Output
PID PGID SID TTY TIME CMD
5119 5119 5117 pts/2 00:00:02 zsh

Now, head back to the terminal where your program is being launched and click Enter to start the _daemon function. After then, look once more at the process information that is displayed on the other terminal.

ps -C test -o “pid ppid pgid sid tty stat command”
# Output
PID PPID PGID SID TT STAT COMMAND
22504 1 22481 5117 pts/2 S ./test

To begin, given that you do not see the plus sign (plus) in the STAT field, it is safe to assume that the newly created subprocess is now operating in the background. Now, using the following command, check to see who the process’s parent process is:

ps -jp 1
​​​​​​​# Output
PID PGID SID TTY TIME CMD
1 1 1 ? 00:00:01 systemd

You are now able to see that the systemd process is the parent process of the process you are working on. In the previous section, it was specified that the following part of the procedure should involve opening a new session while also disconnecting the process from the control terminal. You may accomplish this by use the setsid function. Include this call in the function that you have named _daemon.

The following is the piece of code that needs to be added:

if (setsid() == -1)
return -1;

You are free to delete the initial getchar function from the test.c code now that you have examined the state that existed prior to the _daemon call being made.

//test.c
#include <stdio.h>
int _daemon(int, int);
int main()
{
_daemon(0, 0);
getchar();
return 0;
}

After the program has been compiled and ran once more, you should return to the terminal where you made your evaluations. The current standing of your procedure is as described below:

ps -C test -o “pid ppid pgid sid tty stat command”
​​​​​​​# Output
PID PPID PGID SID TT STAT COMMAND
25494 1 25494 25494 ? Ss ./test

The presence of a question mark in the TT field denotes that the connection between your process and a terminal has been severed. It should be brought to your attention that the PID, PGID, and SID values of your process are all identical. Your procedure is now the leader of the session.

The following step will need you to alter the working directory so that it points to the root directory. This will be done in accordance with the value of the parameter that you gave. You may accomplish this by inserting the code shown below into the _daemon function:

if (!nochdir) {
if (chdir(“/”) == -1)
return -1;
}

Now, based on the argument that was supplied, it is possible to shut any and all file descriptors. In the method called _daemon, add the following line of code:

#define NR_OPEN 1024
if (!noclose) {
for (i = 0; i < NR_OPEN; i++)
close(i);
open(“/dev/null”, O_RDWR);
dup(0);
dup(0);
}

Once all of the file descriptors have been closed, the new files that are opened by the daemon will be shown with the descriptors 0, 1, and 2 correspondingly. In this particular scenario, for instance, the printf instructions included in the code will be written to the second file that has been opened. In order to prevent this from happening, the first three identifiers refer to the device labeled /dev/null.

In this particular scenario, the _daemon function will arrive at its ultimate state as follows:

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
int _daemon(void) {
// PID: Process ID
// SID: Session ID
pid_t pid, sid;
pid = fork(); // Fork off the parent process
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
// Create a SID for child
sid = setsid();
if (sid < 0) {
// FAIL
exit(EXIT_FAILURE);
}
if ((chdir(“/”)) < 0) {
// FAIL
exit(EXIT_FAILURE);
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
while (1) {
// Some Tasks
sleep(30);
}
exit(EXIT_SUCCESS);
}

The following is an illustration of a piece of code that acts as a daemon and executes the sshd application:


if (!(debug_flag || inetd_flag || no_daemon_flag)) {
int fd;
if (daemon(0, 0) < 0)
fatal(“daemon() failed: %.200s”, strerror(errno));
/* Disconnect from the controlling tty. */
fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
if (fd >= 0) {
(void) ioctl(fd, TIOCNOTTY, NULL);
close(fd);
}
}

It Is Essential to Have Daemons When Programming a Linux System

Daemons are programs that carry out a variety of tasks in a manner that has been predetermined and is established in reaction to particular occurrences. They do not make any noise when operating on your Linux system. The user does not have direct control over them, and each service that operates in the background has its own daemon that manages it.

In order to discover the structure of the kernel used by the Linux operating system and to comprehend how the many types of system architectures function, it is essential to become proficient with daemons.

Alex
We will be happy to hear your thoughts

Leave a reply

TopBestProductReview
Logo