Advanced Programming in UNIX environment-daemon process

Source: Internet
Author: User

1. Introduction to daemon

Daemon processes are the background service processes in Linux. It is a long-lived process, usually independent of the control terminal and periodically executes a task or waits to process some events. Daemon is often started during system boot and ended when the system is shut down. In Linux, there are many daemon processes. Most services are implemented through daemon. At the same time, daemon can complete many system tasks, for example, job planning process crond and printing process lqd (the ending letter D indicates Daemon ).

For details, see chapter 1 of apue.

Ii. Significance of daemon

In Linux, every system interface that communicates with users is called a terminal. Every process starting from this terminal is attached to this terminal, which is called the control terminal of these processes, when the control terminal is closed, the corresponding process is automatically closed. However, the daemon can break through this restriction. It does not exit until it is executed. To prevent a process from being affected by user, terminal, or other changes, you must turn the process into a daemon.

 

3. Daemon creation process

1. Create a child process and the parent process exits.

Because the daemon process exists independently from the terminal, this step creates the illusion that a process exits after it completes running. When the child process that is detached from the parent process exists independently, the child process will become an orphan process, and will be immediately adopted by the linux1 process (init) and become the child process of init.

2. Create a session in the sub-process

Process Group: A collection of one or more processes. A process group is uniquely identified by a process group ID. In addition to the process ID (PID), the process group ID is also a required attribute of a process. Each process group has a leader process. The process ID of the leader process is equal to the Process Group ID. The process group ID will not be affected by the exit of the leader process.

Session cycle: a set of one or more Process Groups. Generally, a session starts to log on to the user and ends when the user exits. During this period, all processes run by the user belong to this session period.

Next, we will introduce the related content of setsid:

1. Functions of setsid:

The setsid function is used to create a new session and act as the group leader. Calling setsid has the following three functions:

Remove the process from the control of the original session

Remove the process from the control of the original Process Group

Remove the process from the control of the original control terminal

2. Significance of the setsid function:

The fork function is called to create a child process in the first step of daemon creation, and then the parent process is exited. When the fork function is called, the sub-process completely copies the session period, process group, and control terminal of the parent process. Although the parent process exits, however, the session period, process group, and control terminal are not changed. Therefore, it is not truly independent, and the setsid function can make the process completely independent, to get rid of the control of other processes.

 

3. Change the current directory to the root directory.

This step is also necessary. The child process created using fork inherits the current working directory of the parent process. Because the file system in the current directory (such as "/mnt/USB") cannot be detached while the process is running, this will cause a lot of trouble for future use (for example, the system needs to enter the single-user mode for some reason ). Therefore, the common practice is to make "/" the current working directory of the daemon, so as to avoid the above problems. Of course, if you have special requirements, you can also change the current working directory to another path, such as/tmp. Change the common functional chdir of the working directory.

 

4. Reset the File Permission mask.

The File Permission mask is used to block the corresponding bits in the file permission. For example, if a File Permission mask is 050, the file group owner's read and executable permissions are blocked. Because the child process created using the fork function inherits the File Permission mask of the parent process, this causes a lot of trouble for the child process to use files. Therefore, setting the File Permission mask to 0 greatly enhances the flexibility of the daemon process. The UMASK function is used to set the File Permission mask. Here, the general usage is umask (0 ).

 

5. Disable the file descriptor.

Like the File Permission Code, the child process created using the fork function will inherit some opened files from the parent process. These opened files may never be read or written by the daemon, But they consume the same system resources and may cause the file system to be unable to be detached.

After step 2, the daemon has lost contact with the control terminal. Therefore, the characters entered from the terminal cannot reach the daemon process, and the characters output by conventional methods (such as printf) in the daemon cannot be displayed on the terminal. Therefore, the three files whose file descriptors are 0, 1, and 2 (input, output, and error) have lost value and should be disabled.

Write your own daemon as long as you follow a specific process.

Step 1: create a child process and exit the parent process;

PID = fork ()

If(PID
> 0)
{
Exit (0); // The parent process exits.
}

Step 2: Create a session in the sub-process;

Step 3: change the current directory to the root directory;

Step 4: reset the File Permission mask;

Step 5: Disable the file descriptor;

In this way, a daemon is created.

Let's take a look at the example below: This daemon writes a sentence to the log file/tmp/daemon. log every 10 seconds.

  1. #Include
    <Stdlib. h>
    #Include
    <Stdio. h>
    #Include
    <String. h>
    #Include
    <Fcntl. h>
    #Include
    <Sys/types. h>
    #Include
    <Unistd. h>
    #Include
    <Sys/Wait. H>

    IntMain ()
    {
    Pid_t PID;
    IntI, FD;
    Char* Buf
    = "This is a daemon \ n ";

    PID = fork (); // The first step is to create a sub-process and the parent process exits.

    If(PID
    <0)
    {
    Printf ("error fork \ n ");
    Exit (1 );
    }
    ElseIf(PID
    > 0)
    {
    Exit (0); // The parent process exits.
    }
    Setsid (); // Step 2 create a session in the child process
    Chdir ("/");
    // Step 3 change the current directory to the root directory
    Umask (0); // reset the File Permission mask in Step 4
    For(I
    = 0; I <getdtablesize (); I ++) // closes the file descriptor in step 5.
    {
    Close (I );
    }
    // Map 0/1/2 To Dev/null
    // At this time, the daemon process has been created. The daemon process starts to work.
    While(1)
    {
    If(FD
    = Open ("/tmp/daemon. log ",
    O_creat | o_wronly | o_append, 0600 ))
    <0)
    {
    Printf ("Open File error \ n ");
    Exit (1 );
    }
    Write (FD, Buf, strlen (BUF) + 1 );
    Close (FD );
    Sleep (10 );
    }
    Exit (0 );
    }

1. Introduction to daemon

Daemon processes are the background service processes in Linux. It is a long-lived process, usually independent of the control terminal and periodically executes a task or waits to process some events. Daemon is often started during system boot and ended when the system is shut down. In Linux, there are many daemon processes. Most services are implemented through daemon. At the same time, daemon can complete many system tasks, for example, job planning process crond and printing process lqd (the ending letter D indicates Daemon ).

For details, see chapter 1 of apue.

Ii. Significance of daemon

In Linux, every system interface that communicates with users is called a terminal. Every process starting from this terminal is attached to this terminal, which is called the control terminal of these processes, when the control terminal is closed, the corresponding process is automatically closed. However, the daemon can break through this restriction. It does not exit until it is executed. To prevent a process from being affected by user, terminal, or other changes, you must turn the process into a daemon.

 

3. Daemon creation process

1. Create a child process and the parent process exits.

Because the daemon process exists independently from the terminal, this step creates the illusion that a process exits after it completes running. When the child process that is detached from the parent process exists independently, the child process will become an orphan process, and will be immediately adopted by the linux1 process (init) and become the child process of init.

2. Create a session in the sub-process

Process Group: A collection of one or more processes. A process group is uniquely identified by a process group ID. In addition to the process ID (PID), the process group ID is also a required attribute of a process. Each process group has a leader process. The process ID of the leader process is equal to the Process Group ID. The process group ID will not be affected by the exit of the leader process.

Session cycle: a set of one or more Process Groups. Generally, a session starts to log on to the user and ends when the user exits. During this period, all processes run by the user belong to this session period.

Next, we will introduce the related content of setsid:

1. Functions of setsid:

The setsid function is used to create a new session and act as the group leader. Calling setsid has the following three functions:

Remove the process from the control of the original session

Remove the process from the control of the original Process Group

Remove the process from the control of the original control terminal

2. Significance of the setsid function:

The fork function is called to create a child process in the first step of daemon creation, and then the parent process is exited. When the fork function is called, the sub-process completely copies the session period, process group, and control terminal of the parent process. Although the parent process exits, however, the session period, process group, and control terminal are not changed. Therefore, it is not truly independent, and the setsid function can make the process completely independent, to get rid of the control of other processes.

 

3. Change the current directory to the root directory.

This step is also necessary. The child process created using fork inherits the current working directory of the parent process. Because the file system in the current directory (such as "/mnt/USB") cannot be detached while the process is running, this will cause a lot of trouble for future use (for example, the system needs to enter the single-user mode for some reason ). Therefore, the common practice is to make "/" the current working directory of the daemon, so as to avoid the above problems. Of course, if you have special requirements, you can also change the current working directory to another path, such as/tmp. Change the common functional chdir of the working directory.

 

4. Reset the File Permission mask.

The File Permission mask is used to block the corresponding bits in the file permission. For example, if a File Permission mask is 050, the file group owner's read and executable permissions are blocked. Because the child process created using the fork function inherits the File Permission mask of the parent process, this causes a lot of trouble for the child process to use files. Therefore, setting the File Permission mask to 0 greatly enhances the flexibility of the daemon process. The UMASK function is used to set the File Permission mask. Here, the general usage is umask (0 ).

 

5. Disable the file descriptor.

Like the File Permission Code, the child process created using the fork function will inherit some opened files from the parent process. These opened files may never be read or written by the daemon, But they consume the same system resources and may cause the file system to be unable to be detached.

After step 2, the daemon has lost contact with the control terminal. Therefore, the characters entered from the terminal cannot reach the daemon process, and the characters output by conventional methods (such as printf) in the daemon cannot be displayed on the terminal. Therefore, the three files whose file descriptors are 0, 1, and 2 (input, output, and error) have lost value and should be disabled.

Write your own daemon as long as you follow a specific process.

Step 1: create a child process and exit the parent process;

PID = fork ()

If(PID
> 0)
{
Exit (0); // The parent process exits.
}

Step 2: Create a session in the sub-process;

Step 3: change the current directory to the root directory;

Step 4: reset the File Permission mask;

Step 5: Disable the file descriptor;

In this way, a daemon is created.

Let's take a look at the example below: This daemon writes a sentence to the log file/tmp/daemon. log every 10 seconds.

  1. #Include
    <Stdlib. h>
    #Include
    <Stdio. h>
    #Include
    <String. h>
    #Include
    <Fcntl. h>
    #Include
    <Sys/types. h>
    #Include
    <Unistd. h>
    #Include
    <Sys/Wait. H>

    IntMain ()
    {
    Pid_t PID;
    IntI, FD;
    Char* Buf
    = "This is a daemon \ n ";

    PID = fork (); // The first step is to create a sub-process and the parent process exits.

    If(PID
    <0)
    {
    Printf ("error fork \ n ");
    Exit (1 );
    }
    ElseIf(PID
    > 0)
    {
    Exit (0); // The parent process exits.
    }
    Setsid (); // Step 2 create a session in the child process
    Chdir ("/");
    // Step 3 change the current directory to the root directory
    Umask (0); // reset the File Permission mask in Step 4
    For(I
    = 0; I <getdtablesize (); I ++) // closes the file descriptor in step 5.
    {
    Close (I );
    }
    // Map 0/1/2 To Dev/null
    // At this time, the daemon process has been created. The daemon process starts to work.
    While(1)
    {
    If(FD
    = Open ("/tmp/daemon. log ",
    O_creat | o_wronly | o_append, 0600 ))
    <0)
    {
    Printf ("Open File error \ n ");
    Exit (1 );
    }
    Write (FD, Buf, strlen (BUF) + 1 );
    Close (FD );
    Sleep (10 );
    }
    Exit (0 );
    }

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.