How to Create a Daemon on Linux

Daemons are processes that do not run directly under the control of the user, but run in the background. Usually, they start at system startup and run continuously until the system shuts down. The only difference between these processes and the normal process is that they do not send messages to the console or screen in any way.

This is how you can create a daemon on a Linux machine.

A brief introduction to how Daemons are created

Many daemons run on the system and some examples of familiar daemons are as follows:

  • crond: Makes commands run at specified time
  • sshd: Allow login to the system from remote machines
  • httpd: Provide web pages
  • nfsd: Allow file sharing over network

Also, daemon processes are often named to end with the letter dalthough it is not required.

In order for the process to run as a daemon, follow the following path:

  • Initial operations, such as reading configuration files or obtaining necessary system resources, must be performed before the process becomes a daemon. In this way, the system can report received errors to the user and the process will be terminated with an appropriate error code.
  • A background process is created with init as its parent process. For this purpose, a subprocess is detached from the first init process, and then the above process is terminated with exit.
  • A new session will be opened by calling the setid function and the process will be disconnected from the terminal.
  • All open file descriptors inherited from the parent process are closed.
  • Standard input, output and error messages are redirected to /dev/null.
  • The working directory of the process must be changed.

MAKE A VIDEO OF THE DAY

What is Daemon version?

After logging into the system through the terminal, the user can run many applications through the shell program. These processes will close when the user exits the system. The operating system groups these processes into session and process groups.

Each session consists of groups of processes. You could describe this situation as follows:

The terminal where processes receive their input and send their output is called the control terminal. A control terminal is only associated with one session at a time.

A session and process groups that have identifiers (IDs); these identifiers are the process identifiers (PIDs) of the session and process group leaders. A child process shares the same pool as its parent process. When multiple processes are communicating with the pipeline mechanism, the first process becomes the process group leader.


Create Daemon Process on Linux

Here you will see how you can create a daemon function. For this purpose, you will create a function named _daemon. You can start by naming the application code that will run as daemon like test.cand the code in which you will create the daemon function as daemon.c.


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


#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();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
return 0;
}


To create a daemon, you need a background process whose parent process is init. In the above code, _daemon create a child process and then kill the parent process. In this case, your new process will be a subprocess of init and will continue to run in the background.

Now compile the application with the following command and check the status of the process before and after _deamon called:

gcc -o test test.c daemon.c

Run the application and switch to another terminal without pressing any other key:

./test

You can see that the values ​​related to your process are as follows. Here you will have to use the ps command to get process related information. In this case, _daemon function has not been called yet.

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


When you look at STAT you see that your process is running but is waiting for an unscheduled event to happen that will cause it to run in the foreground.

Abbreviation Means
S Sleeping waiting for an event to happen
BILLION Application has stopped
S Session leader
+ The application is running in the foreground

You may find that your application’s main process is the shell as expected.

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

Now go back to the terminal where you are running your application and press enter to call out _daemon Constan. Then review the process information on another terminal.

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

First of all, you can tell that the new subprocess is running in the background because you can’t see it + character in STAT field. Now check who is the process’s parent using the following command:

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

Now you can see that the main process of your process is systemd process. It was mentioned above that for the next step a new session will open and the process should be disconnected from the control terminal. For this you use the setid function. Add this call to yours _daemon Constan.

The code to add is as follows:

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

You have now checked the previous status _daemon called, now you can delete the first one getchar function in test.c code.


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

After compiling and running the application again, go to the terminal where you performed your evaluations. The new state of your process is as follows:

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

The ? log in TT field indicates that your process is no longer connected to the terminal. Note that PID, PGIDand SID the values ​​of your process are the same. Your process is now a session leader.

In the next step, change the working directory to the root directory according to the value of the argument you passed. You can add the following code in _daemon this function:

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

Now, according to the passed argument, all file descriptors can be closed. Add the following code _daemon Constan:


if (!noclose) {
for (i = 0; i < NR_OPEN; i++)
close(i);
open("/dev/null", O_RDWR);
dup(0);
dup(0);
}

After all file descriptors are closed, new files opened by the daemon will be displayed with descriptors 0, 1 and 2 respectively. In this case, for example, printf commands in the code will be redirected to the second file opened. To avoid this, the first three identifiers point to /dev/null device.

In this case, the final state of _daemon The function will be 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_t pid, sid;
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
// Create a SID for child
sid = setsid();
if (sid < 0) {
exit(EXIT_FAILURE);
}
if ((chdir("/")) < 0) {
exit(EXIT_FAILURE);
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
while (1) {
sleep(30);
}
exit(EXIT_SUCCESS);
}


Here is an example of the code that runs sshd app like a daemon:

...
if (!(debug_flag || inetd_flag || no_daemon_flag)) {
int fd;
if (daemon(0, 0) < 0)
fatal("daemon() failed: %.200s", strerror(errno));
fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
if (fd >= 0) {
(void) ioctl(fd, TIOCNOTTY, NULL);
close(fd);
}
}
...

Daemon is very important for Linux system programming

Daemons are programs that perform various actions in a predefined manner set up in response to certain events. They run silently on your Linux machine. They are not under direct user control, and each background service has its own daemon.

It is important to master daemons to learn the kernel structure of the Linux operating system and understand the workings of different system architectures.



Close-up of an ethernet cable plugged into a router.

Continue reading


About the author

https://www.makeuseof.com/create-daemons-on-linux/ How to Create a Daemon on Linux

Sarah Ridley

USTimesPost.com is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – admin@ustimespost.com. The content will be deleted within 24 hours.

Related Articles

Back to top button