Linux daemon basics

Source: Internet
Author: User
Tags sigint signal
1. basic concepts involved in Daemon 1.1 Process Group 1.1.1 Process Group basic concepts process groups are a collection of one or more processes that can receive various signals from the same terminal. Each running program or command generates a process Group. Each process belongs to a process Group, and each process belongs to... information &

1. basic concepts involved in the daemon


1.1 Process Group
1.1.1 Basic concepts of process groups
A process Group is a collection of one or more processes that receive various signals from the same terminal. Each running program or command generates a process Group.

Each process belongs to a process Group, and each process Group has a lead process (or group leader process). Generally, the first process in a process Group is the lead process. A lead process can create a process Group and a process in the group. The child process from the leading process fork will also be in this process Group. once the child process executes the exec and other exit functions, it will no longer belong to this process Group.

 


Life cycle of a process Group: The life cycle of the process Group from creation to the last process exit. The departure of the last process in the group can be terminated or added to another process. The life cycle of a process Group is irrelevant to the termination of the process leader. if a process exists, the life cycle of the process Group is not completed.

1.1.2 related commands
1. view the pid of all process groups (that is, the pid of the lead process): ps-A-o pgrp = | sort | uniq

2. view the pid of a process Group: ps-C process name-o pgrp =

3. obtain the pid of the pidof process based on the process name.

4. obtain the process name based on the process pid: ps-aux | grep process pid.

5. obtain the specific information of a process: ps-ef | grep process name or process pid

1.1.3 related functions
# Include

Pid_t getpgrp (); // Obtain the pid of the process Group, that is, the pid of the lead process in the group, which is equivalent to calling getpgid (0)

Pid_t getpid (); // Obtain the pid of the current process

Pid_t getppid (); // Obtain the parent pid of the current process

Pid_t getpgid (); // returns the pid of the process Group of the specified process.

Int setpgid (pid_t pid, pid_t pgid);/* Set the pid process Group id to pgid. if the two parameters are equal,

* The process specified by the pid becomes the process group leader. If the pid is 0, the process

* The Group id is pgid. if the pgid is 0, the process Group id is pid. */

Int setpgrp (); // Set the pid of the process group to which the current process belongs to, equivalent to setpgid (0, 0)

1.2 Sessions
1.2.1 Basic concepts of sessions
A single login forms a session. a session can contain multiple process groups (www.linuxidc.com, one foreground process Group and multiple background process groups), but only one foreground process group can be created.

1.2.2 related functions
# Include

Pid_t setsid ();

When the process that calls this function is not the lead process of the process Group, the function can create a new session. After the function is successfully called, the calling process becomes the leading process of the new session and the leading process of the new process, and the process loses control terminal.

1.3 Control Terminal
There are leading processes in the process Group. Similarly, there should also be leading processes in sessions. After a session lead process opens a terminal, the terminal becomes the session control terminal. the session lead process that establishes a connection with the control terminal becomes the session leader ). One session can only have one control terminal, and one control terminal can only have one session. The input and signal generated on the control terminal (for example, pressing ctrl + c generates a SIGINT signal) will be sent to all processes in the foreground process Group of the session.

2. daemon process and its features
1. the most important feature of the daemon process is that it runs in the background;

2. the daemon must be isolated from the environment before running. These environments include unclosed file descriptors, control terminals, sessions and process groups, and working directories. these environments are generally inherited from the parent processes (especially Shell) that execute them.

3. the daemon can start from the script/etc/rc at Linux startup. d, which can be started by the job planning process crond or by the user terminal (usually Shell.

3 daemon programming
You can transform a common process into a daemon process based on the features of the daemon.

3.1 background running features
Run daemon in the sub-process.

If (pid = fork ())

{

Exit (0); // the parent process ends and the child process continues.

}

3.2 environment disconnection
3.2.1 remove process groups, logon sessions, and control terminals
Process groups, logon sessions, and control terminals are inherited from the parent process. to avoid their impact, control terminals must get rid of them. The specific method is to call the setsid function.

If (pid = fork () {exit (0);} generates a sub-process, which ensures that the process that calls setsid is not the leading process in the process Group. After the setsid call is successful, the sub-process becomes the lead process in the new session and the lead process in the process Group, and is out of the original session, process group and control terminal.

3.2.2 prohibit the process from opening the control terminal
If (pid = fork ())

{

Exit (0); // The Child process ends and a child process is generated.

}

Terminate the sub-process and generate a new sub-process. The new sub-process is not a session-leading process, so you cannot open the control terminal. In this way, the process is prohibited from opening the control terminal.

3.2.3 detaching open file descriptors
A process inherits the opened file descriptor from its parent process. If you do not close the file system, system resources will be wasted. at the same time, the file system where the process is located cannot be detached and other unexpected errors will occur.

Max_fd = sysconf (_ SC _OPEN_MAX );

For (I = 0; I <max_fd; I ++)

{

Close (I );

}


3.2.4 remove from the current working directory
When a process is active, the file system in which the working directory is located cannot be uninstalled. Generally, you need to switch the working directory to the root directory. For processes that need to run logs, change the working directory to a specific directory.

Chdir ("/");

3.2.5 resetting the file permission mask

The permission mask of the file inherited by the process from its parent process. it may modify the permission of the file created by the Daemon. the mask must be clear.

Umask (0 );

3.2.6 process SIGCHLD signal
It is not necessary to process SIGCHLD signals. However, for some processes, www.linuxidc.com, especially server processes, usually generate subprocesses to process requests when requests arrive. If the parent Process does not wait for the completion of the child Process (without calling wait or waitpid), the child Process will become a Zombie Process and occupy system resources. If the parent process waits for the child process to end, it will increase the burden on the parent process and affect the concurrent performance of the server process. In Linux, you can set SIGCHLD to SIG_IGN, so that the kernel will not generate zombie processes when the child process ends.

Signal (SIGCHLD, SIG_IGN); // shield the SIGCHLD signal

This is a technique commonly used to improve the performance of concurrent servers. When the server process does not call wait to clean up sub-processes and generates zombie sub-processes, if the SIGCHLD signal is blocked, the kernel will forward the sub-processes to the init process for processing.

4 daemon example
# Include
# Include
# Include
# Include
# Include
# Include

Void init_daemon ()
{

Int pid;
Int I;
Int max_fd;


If (pid = fork ())
{
Exit (0); // the parent process ends and the child process continues.
}
Else if (pid <0)
{
Exit (1); // fork failed
}

Setsid ();

If (pid = fork ())
{
Exit (0); // The Child process ends and a new child process is generated.
}
Else if (pid <0)
{
Exit (1); // fork error, exit
}

/* Close the opened file descriptor */
Max_fd = sysconf (_ SC _OPEN_MAX );

For (I = 0; I <max_fd; I ++)
{
Close (I );
}

/* Switch the working directory */
Chdir ("/tmp ");


/* Reset the file creation mask */
Umask (0 );

Return;

}

Int main ()
{

FILE * fp = NULL;

Signal (SIGCHLD, SIG_IGN );

Init_daemon ();

While (1)
{

Sleep (1 );
If (fp = fopen ("/mnt/hgfs/Share/unix/test. log", ""))! = NULL)
{
Fprintf (fp, "% s \ n", "test message ");
Fclose (fp );
}
}

Return 0;
}
Compilation: gcc-o daemon. c

Run:./daemon

View daemon: ps-ef | grep daemon

 

View the files generated by the Daemon:

 

Author: "Orion's blog"
 

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.