The daemon process under Linux

Source: Internet
Author: User
Tags session id sigint signal

Transferred from: http://www.cnblogs.com/xuxm2007/archive/2011/07/29/2121280.html

#include <unistd.h>
int daemon (int nochdir,int noclose)
When creating sprite processes, it is often necessary to modify the working directory of the sprite process to the "/" root directory
and redirect the standard input, output, and error output to/dev/null
The daemon function is to modify the root directory to the working directory when the parameter nochdir is 0 o'clock.
Noclose for 0 o'clock, do input, output and error output redirect to/dev/null
Execution successful return 0
Error returned-1

<----------------------------------------->

A brief analysis of the story behind the creation of Daemon daemon
#include <unistd.h>
int main (int argc, char *argv[])
{
...
if (daemon (0, 0)) {//Call glibc library function daemon, create daemon daemon
Perror ("daemon");
return-1;
}
All right, this is daemon's child process. [Luther.gliethttp].
...
}
=========================================================
int daemon (int nochdir, int noclose)
{
pid_t pid;
if (!nochdir && chdir ("/")! = 0)//If nochdir=0, then change to "/" root directory
return-1;
if (!noclose)//If no close
{
int fd = open ("/dev/null", O_RDWR);//Open empty file.
if (FD < 0)
return-1;
For each process, it's FDS file descriptor table: 0,1 and 2 file handle locations correspond to the FoPs file operand set,
FDT-&GT;FD[0],FDT-&GT;FD[1],FDT-&GT;FD[2],
The regulation will be related to standard input, standard output, and standard error output respectively [Luther.gliethttp].
Therefore, when the user application calls the Open function, the default is to start the file with the 3 index, so the minimum file handle returned by the current open is 3[luther.gliethttp].
dup2 (unsigned int oldfd, unsigned int newfd) system call is to use OLDFD fops operation file Set files, copy to NEWFD where
i.e.: fdt->fd[newfd] = fdt->fd[oldfd];
if (dup2 (FD, 0) < 0 | |//Use the/dev/null fops function set of the character device to replace the set of file operations corresponding to the 0 handle.
Dup2 (FD, 1) < 0 | | Replaces the set of file operations corresponding to the 1 handle using the FoPs function set of the character device/dev/null.
Dup2 (FD, 2) < 0)///dev/null the FoPs function set with the character device, replacing the set of file operations corresponding to the 2 handle.
{
Close (FD);
return-1;
}
If the above substitution succeeds, then any action on the keyboard will not have any effect on the process, because the FoPs file operation set where the 0,1,2 handle is located has already become,

//被重定向为"/dev/null"空洞设备的fops.所以对0,1,2句柄的读写操作,也就是在对/dev/null设备作读写操作.
close(fd);//关闭打开的/dev/null
}
   pid = fork();//创建子进程.
if (pid < 0)
return -1;
if (pid > 0)
    _exit(0);//返回执行的是父进程,那么父进程退出,让子进程变成真正的孤儿进程.
//ok,我们期望的daemon子进程执行到这里了.
if ( setsid() < 0 )//设置session id.
return -1;
return 0;//成功创建daemon子进程[luther.gliethttp].
}

Http://docs.linuxtone.org/ebooks/C&CPP/c/ch34s03.html

http://blog.csdn.net/yyyzlf/article/details/5267954

Due to the nature of the daemon, the process of writing daemons must obey certain rules. This section describes the key points of these rules and gives the relevant code.

8.2.1 steps to implement a daemon

In a Linux system, the following steps must be followed in order to implement a daemon process.

1. Make the init process the parent process of the newly generated process.

After calling the fork function to create the child process, the parent process exits immediately. In this way, the resulting subprocess becomes an orphan process and is taken over by the Init process, and the resulting new process becomes run in the background.

2. Call the Setsid function

By calling the Setsid function, the newly created process leaves the control terminal, creates a new process group, and becomes the first process of the process group. To give the reader a better understanding of this step, the following is the basic concept of a process group, session.

In a Linux system, all processes belong to their own group of processes. A process group is a collection of one or more processes. For example, you can think of a class as a process group, where members are processes. A class has at least one member. When the last member of a class does not exist, the class does not exist, that is, the process group dies.

Each process group has an identity that is similar to the process number, called the process group ID. The process group ID is determined by the process number of the lead process, and there is a lead process for each process group. The presence or absence of a process group is not related to the presence of the lead process.

A session is a collection of one or more process groups. Like a process group, there is a lead process for each session. Linux is a multi-user operating system in which multiple processes belonging to different users exist in the system at the same time. If a user sends a signal on a terminal, for example, by pressing "CTRL + C" to send a SIGINT signal, how to ensure that the signal is correctly sent to the corresponding process without affecting the process of the user using the other terminal?

Sessions and process groups are the methods that the Linux kernel uses to manage user processes in multi-user situations. Each process belongs to a process group, and the process group belongs to a session. When a user logs on to the system from the terminal (whether it is a terminal or a pseudo-terminal), a new session is created. Processes that are started on the terminal will be placed in the process group of the session by the system.

A process in a session is connected to a terminal through the lead process in the session (often referred to as the control process). The terminal is the control terminal of the session. A session can have only one control terminal, and vice versa. If a session has a control terminal, it must have a foreground process group. Processes that belong to this group can get input from the control terminal. At this point, the other process groups are background process groups. Figure 8.3 shows the relationship between the session, the process group, the process, and the control terminal.

Figure 8.3 Relationship between session, process group, process and control terminal

Because the daemon does not control the terminal, and the child process created with the Fork function inherits the control terminal, session, and process group of the parent process, a new session must be created to disengage from the parent process. The Linux system provides the SETSID function to create a new session. The information for the SETSID function is shown in table 8.1.

Table 8.1 Setsid functions

Header file

<unistd.h>

function form

pid_t setsid (void);

return value

Success

Failed

Whether to set errno

Session ID of the calling process

? 1

Is

The SETSID function creates a new session and causes the process that invokes the SETSID function to be the lead process for a fresh session. The process that calls the SETSID function is the only process group in the newly created session, and the process group ID is the process number of the calling process. The SETSID function produces this result with a condition that the calling process is not the lead process for a process. Because the parent process that called fork in the first step exits, the child process cannot be the lead process for the process group. The lead process for this session has no control over the terminal to be connected. At this point, the daemon does not have to control the terminal requirements.

3. Change the current working directory

The child processes that are produced by using the fork function inherit the current working directory of the parent process. When a process does not end, its working directory cannot be unloaded. To prevent this from happening, the daemon typically changes its working directory to the root directory (/directory). The function used to change the working directory is chdir.

4. Close file descriptors and redirect standard input, output, and error outputs

The newly generated process inherits some open file descriptors from the parent process, and if you do not use these file descriptors, you need to close them. Daemons are running in the background of the system and should not have any output information at the terminal. You can use the DUP function to redirect standard input, output, and error output to a/dev/null device (/dev/null is an empty device and no output is written to it). The specific code is given below:

...

int FD;

REDIRECT standard input output to an empty device

FD = open ("/dev/null", O_RDWR, 0);

if (FD! =-1)

{

Dup2 (FD, Stdin_fileno);

Dup2 (FD, Stdout_fileno);

Dup2 (FD, Stderr_fileno);

if (FD > 2)

Close (FD);

}

...

5. Set the file permission creation mask for the daemon

In many cases, the daemon creates some temporary files. For security reasons, it is often not desirable for these files to be viewed by other users. At this point, you can use the Umask function to modify the file permissions and create a mask value to meet the requirements of the daemon.

8.2.2 Daemon Process Specific implementation

This section gives an instance of a daemon creation. The daemon function is defined in program p8.1.c to enable the creation of daemons. The idea of its creation is described in detail in 8.2.1, and the specific code of the program is as follows:

Implementation of the P8.1.C daemon process

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

/* The daemon function is used to convert the process that invokes the function into a daemon */

Int

Daemon (int nochdir, int noclose)

{

pid_t pid;

PID = fork ();

/* If the creation process fails */

if (PID < 0)

{

Perror ("fork");

return-1;

}

/* Parent Process exits run */

if (pid! = 0)

Exit (0);

/* Become the session leader process */

PID = Setsid ();

if (PID <-1)

{

Perror ("Setsid");

return-1;

}

/* Modify working directory to root directory */

if (! Nochdir)

ChDir ("/");

/* Redirect the standard input output to the empty device */

if (! Noclose)

{

int FD;

FD = open ("/dev/null", O_RDWR, 0);

if (FD! =-1)

{

Dup2 (FD, Stdin_fileno);

Dup2 (FD, Stdout_fileno);

Dup2 (FD, Stderr_fileno);

if (FD > 2)

Close (FD);

}

}

Umask (0027);

return 0;

}

int main (void)

{

Daemon (0,0);

Sleep (1000);

return 0;

}

Compile p8.1.c with GCC and get an executable named p8.1. Executing the program, the program will run in the daemon's state, as shown in 8.4.

The daemon process under Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.