Orphan process and daemon process
Through the previous study we learned how to create a process through the fork () function and the vfork () function. Now let's go into two special processes: The orphan process and the daemon.
I. The orphan process
1. What is the orphan process
If a child process's parent process ends before the child process, the child process becomes an orphan process, which is adopted by the INIT process and becomes a child of the INIT process.
2. So how do you turn a process into an orphan process?
We can create a process first, then kill its parent process, then it becomes an orphan process.
PID = fork ();
if (PID > 0) {
Exit (0);
}
3. Examples of functions:
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <sys/types.h>
4 #include <stdlib.h>
5
6 int Main ()
7 {
8 pid_t pid;
9 pid = fork ();
Ten if (!pid) {
One while (1) {
printf ("A background process,pid:%d/n,parentid:%d/n", Getpid (), Getppid ());
Sleep (3);
14
15}
16}
+ Else if (pid > 0) {
printf ("I am parent process,my pid is%d/n", getpid ());
Exit (0);
20}
+ Else {
printf ("Process creation failed!/n");
23}
return 0;
25
26}
Program Run Results
I am Parent process,my pid is 2026
A background process,pid:2027
, parentid:2026
[Email protected]:~/work/process_thread/fork2$ A background process,pid:2027
, parentid:1
A background process,pid:2027
, parentid:1
A background process,pid:2027
, parentid:1
A background process,pid:2027
, parentid:1
A background process,pid:2027
, parentid:1
A background process,pid:2027
, parentid:1
Tiger-john Description:
With this approach, you can turn a process into an orphan process. When you want to end an orphan process, you can only end its operation at the Terminal input command: Kill 2027 (Kill orphan process number).
Two daemon processes
1. What is a daemon process?
(daemon) is a process that runs in the background and does not control the connection of the terminal. It is independent of the control terminal and usually performs some sort of task periodically.
Tiger-john Description:So why does the daemon have to run out of the background?
The daemon is detached from the terminal to prevent the information in the process from being displayed on any terminal and the process will not be interrupted by terminal information generated by any terminal
2. Why to introduce daemons:
Because in Linux, each system communicates with the user interface called the terminal, every process that starts from this terminal will be attached to this terminal, this terminal is called the control terminal of these processes, when the control terminal is closed, the corresponding process will automatically shut down. But the daemon is able to break through this limitation, and it will start running from execution until the entire system shuts down.If you want a process to not be affected by changes in the user or terminal or otherwise, you must turn this process into a daemon。
3. Features of the daemon
The most important feature of the 1> daemon is running in the background.
2> second, the daemon must be isolated from the environment before it runs. These environments include file descriptors that are not closed, control terminals, session and process groups, working directories, and file creation masks. These environments are typically inherited by daemons from the parent process that executes it, especially the shell.
3> Finally, the way the daemon is started has its special place. It can be started from the startup script/etc/rc.d when the Linux system starts, can be started by the job planning process Crond, and can be performed by the user terminal (usually the shell).
4. Daemons start in a variety of ways:
A. It can be started from the startup script/etc/rc.d when the Linux system starts
B. Can be initiated by the job planning process Crond;
C. It can also be performed by the user terminal (usually the shell).
Tiger-john Summary:
The daemon is a background service process in Linux. It is a long-lived process, usually independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. Daemons often start when the system boots, and terminate when the system shuts down. Linux systems have many daemons, most of which are implemented through daemons, while the daemon can accomplish many system tasks, such as the job planning process Crond, the printing process lqd, and so on (the end letter D is the Daemon meaning).
5. How do I write a daemon?
First step: The first thing to do is to call Umask to set the file mode to create the mask word to 0. Creating a masked word from an inherited file pattern may deny setting certain permissions. For example, if the daemon is to create a group of readable, written files, and the inherited file mode creation mask may block both permissions, then the required group readable, write will not work.
First step: Create child process, parent process exits
1>. Since the daemon is out of control, the first step is to create the illusion that a program has finished running in the shell terminal. All subsequent work is done in the child process, and the user can execute other commands in the Shell terminal to disengage from the control terminal in form.
2> in Linux the parent process exits before the child process and causes the child process to become an orphan process, which is adopted by process 1th (INIT) whenever the system discovers an orphan process.
method is to call fork to produce a child process and then leave the parent process
PID = fork ();
if (0 = = pid)
Exit (0); If it is a parent process, the parent process ends and the child process ends.
This achieves the following: First, if the daemon is started as a simple shell command, then the parent process terminates so that the shell considers that the command has been executed, and second, the child process inherits the process group ID of the parent process, but has a new process ID. This ensures that the child process is not a process group leader. This is necessary for the SETSID call to be done below.
Step Two: Create a new session in the child process:
This step is the most important step in creating the daemon, using the system function Setsid. Make the calling process: (a) The first process of becoming a new session, (b) becoming the lead process for a group of newly-made processes, and (c) not controlling the terminal.
Tiger-john Supplement:Several related concepts
A. Process group: is a collection of one or more processes. The process group has a process group ID to uniquely identify. In addition to the process number (PID), the process group ID (GID) is also an essential attribute of a process. Each process group has a leader process, and the process number of its leader process equals the process group ID. And the process group ID will not be affected by the exit of the leader process.
B. Session period: The session period is a collection of one or more process groups. Typically, a session begins to log on with the user and terminates when the user exits, during which time the process used by the user is part of this session period.
C. A logon session can contain multiple process groups. These process groups share a control terminal. This control terminal is usually the login terminal of the creation process.
Tiger-john Description:Why should they be involved?
Because of the control terminal, logon sessions and process groups are usually inherited from the parent process. We just have to get rid of them and make them unaffected by them.
So how to do it, at this point we can call the Setsid () function on the basis of the first step.
The 1>SETSID function is used to create a new session and serve as the leader of the conversation group. Calling Setsid has the following 3 functions:
Let the process get rid of the control of the original session
Let the process get rid of the control of the original process group
Let the process get rid of the control of the original process group
Let the process get rid of control of the original control terminal
2>. Why would you call the SETSID function when creating a daemon?
Because the first step in creating the daemon calls the fork function to create the child process, and then exits the parent process. Because when the fork function is called, the child process copies the session period of the parent process, the process group, the control terminal and so on, although the parent process exits, but the session period, the process group, the control terminal and so on have not changed, so it is not really independent, and the SETSID function can make the process completely independent, So as to get rid of the control of other processes.
Tiger-john Description:
A. The Setsid () call failed when the process group is the session leader. But the first step has ensured that the process is not the conversation leader.
After the B.setsid () call succeeds, the process becomes the new session leader and the new process leader,and detach from the original login session and the process group。due to the exclusivity of the session process to the control terminal, the process is disconnected from the control terminal。
C. We also prohibit the process from reopening the control terminal at this time
Although the process has become a no-terminal conversation leader. But it can be re-applied to open a control terminal. You can prevent a process from reopening the control terminal by making the process no longer a session leader:
So how does it work?
We can create a child process again, exit the parent process, ensure that the process is not the process leader, and that the process can no longer open a new terminal
PID = fork ();
Exit (0);
Step three: Change the current directory to the root directory
1> the child process created with fork inherits the current working directory of the parent process. Because in the process of running, the current directory is located in the file system can not be uninstalled, which will cause a lot of inconvenience to later use. Therefore, we generally let "/" as the current working directory of the Daemon, so that the above problems can be avoided. If you have special needs, you can also change the current working directory to another path.
2> the common function of changing the working directory is chdir ().
Fourth Step: Reset file Permission Mask
The 1> file permission mask refers to the corresponding bit in the file permission that is masked out. Because the new child process using the Fork function inherits the file permission mask of the parent process, this creates a lot of trouble for the child process to use the file. Therefore, setting the file permission mask to 0 can greatly enhance the daemon's flexibility.
2> the function that sets the file permission mask is umask. The usual method used is umask (0).
Fifth step: Close the file descriptor
1> because the new child process with the fork function inherits some files that have already been opened from the parent process. These open files may never be read and written by the daemon, but they consume system resources as well, and may cause the file system in which they reside to fail to be unloaded.
2> after the second step above, the daemon has lost contact with the owning control terminal. Therefore, characters entered from the terminal cannot reach the daemon, and the characters that are output by the regular methods (such as printf) in the daemon cannot be displayed on the terminal. Therefore, the file descriptor of 0, 1 and 2 of the 3 files (often said input, output and error) has lost its meaning, should also be turned off.
3> Function Example:
for (i=0;i<maxfile;i++)
Close (i);
Sixth step: Handling SIGCHLD Signals
1> processing of SIGCHLD signals is not a must. However, for some processes, in particular, server processes often generate child processes to process requests when requests arrive. If the parent process does not wait for the child process to end, the child process becomes a zombie process (zombie) and thus consumes system resources. If the parent process waits for the child process to end, it increases the burden on the parent process and affects the concurrency performance of the service process.
2> function Implementation:
Signal (sigchld,sig_ign);
This way, the kernel does not spawn a zombie process at the end of the child process.
6 Specific function implementations:
The process of writing a daemon consists of two parts: the main program TEST.C and the initialization program INIT.C.
The Init_daemon function in the initialization program is responsible for generating the daemon. Use the Init_daemon function to generate your own daemon.
Daemon.c
1 #include <stdio.h>
2 #include <signal.h>
3 #include <sys/param.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <stdlib.h>
7
8 int Init_daemon (void)
9 {
Ten pid_t pid;
one int i;
12
PID = fork ();
if (PID > 0) {//First step, end parent process, make child process background
Exit (0);
16}
+ Else if (PID < 0) {
return-1;
19}
20/* The second step is to create a new process group, in which the child process becomes the first process in the process group so that the process is detached from the terminal used */
Setsid ();
22/* Create a new child process again, exit the parent process, ensure that the process is not the process leader, and that the process can no longer open a new terminal */
PID = fork ();
if (PID > 0) {
Exit (0);
26}
else if (PID < 0) {
return-1;
29}
30//Step three: Turn off file descriptors that are no longer needed to inherit from the parent process
for (i = 0;i < Nofile;close (i++));
32//Fourth step: Change the working directory so that the process does not contact any file system
ChDir ("/");
34//Fifth step: Set the file screen Word to 0
Umask (0);
36//Sixth step: Ignore SIGCHLD signal
Panax Notoginseng Signal (sigchld,sig_ign);
return 0;
39}
TEST.c
1 #include <stdio.h>
2 #include <time.h>
3 #include <syslog.h>
4 extern int Init_daemon (void);
5
6 int Main ()
7 {
8 time_t now;
9 Init_daemon ();//Initialize Daemon
Syslog (Log_user | Log_info, "Test daemon!" /n ");
One while (1) {
Sleeps (8);//sleep for one minute
Time (&now);
Syslog (Log_user | Log_info, "System time:/t%s/t/t/n", CTime (&now));
15}
16}
17
Program has been debugged in Ubuntu 2.6 version
[Email protected]:/etc$ gcc-g-o test daemon.c test.c
[Email protected]:/etc$./test
After the compilation is successful, you can view the status of the process with PS-EF
[Email protected]:/etc$ ps-ef
UID PID PPID C stime TTY time CMD
Think 2995 1 0 11:05? 00:00:00./test
From here you can see that the process has the features used by the daemon
View System logs
[Email protected]:~$ cat/var/log/syslog
Nov 11:05:37 Ubuntu test: Testing daemon!
Nov 11:05:45 Ubuntu Test: System time: #011Sat Nov 13 11:05:45 2010#012#011#011
Nov 11:05:53 Ubuntu Test: System time: #011Sat Nov 13 11:05:53 2010#012#011#011
Nov 11:06:01 Ubuntu Test: System time: #011Sat Nov 13 11:06:01 2010#012#011#011
Nov 11:06:09 Ubuntu Test: System time: #011Sat Nov 13 11:06:09 2010#012#011#011
Nov 11:06:17 Ubuntu Test: System time: #011Sat Nov 13 11:06:17 2010#012#011#011
Nov 11:06:25 Ubuntu Test: System time: #011Sat Nov 13 11:06:25 2010#012#011
Linux process Learning-orphan process and daemon