Fork two times how to avoid zombie process collections

Source: Internet
Author: User

 # Include <stdio. h> <br/> # include <sys/Wait. h> <br/> # include <sys/types. h> <br/> # include <unistd. h> </P> <p> int main (void) <br/> {<br/> pid_t PID; </P> <p> If (pid = fork () <0) <br/> {<br/> fprintf (stderr, "fork error! /N "); <br/> exit (-1); <br/>}< br/> else if (pid = 0) /* First child */<br/> {<br/> If (pid = fork () <0) <br/>{< br/> fprintf (stderr, "fork error! /N "); <br/> exit (-1); <br/>}< br/> else if (pid> 0) <br/> exit (0 ); /* parent from second fork = first child */<br/>/* <br/> * We're re the second child; our parent becomes init as soon <br/> * as our real parent callexit () in the statement above. <br/> * Here's where we 'd continue executing, knowing that when <br/> * We're re done, init will reap our status. <br/> */<br/> sleep (2); <br/> printf (" Second child, parent pid = % d/N ", getppid (); <br/> exit (0 ); <br/>}</P> <p> If (waitpid (PID, null, 0 )! = PID)/* Wait for first child */<br/> {<br/> fprintf (stderr, "waitpid error! /N "); <br/> exit (-1 ); <br/>}</P> <p>/* <br/> * We're re the parent (the original process); we continue executing, <br/> * knowing that we're not the parent of the second child. <br/> */<br/> exit (0); <br/>}< br/>

Fork two times in the prevention of death, it is because the son process first exited, the son process was taken over by init, in fact, with the initial parent process out of the relationship, will not be frozen. See the following description of apue p151:

Recall the discussion about dead processes in Section 8. 5. If a process requires f o r k a sub-process, but does not require it to wait
The sub-process is terminated and does not want the sub-process to be frozen until the parent process is terminated. The trick to achieve this is to call f o r k
Twice. The Program 8-5 implements this.
Call s l e p in the second child process to ensure that the first child process is terminated when the parent process I D is printed. After f o r k,
Parent and Child processes can continue to execute-we cannot predict which one will be executed first. If the second child process is not sleep
After f o r k, it may be executed first than its parent process, so the parent process I d it prints will be the parent process that creates it, instead
I n I t process (process ID 1 ).

Other functions of the two forks are daemon:

 Void initasdaemon () <br/>{< br/> If (Fork ()> 0) <br/> exit (0 ); </P> <p> setsid (); </P> <p> signal (SIGINT, sig_ign); <br/> signal (sighup, sig_ign ); <br/> signal (sigquit, sig_ign); <br/> signal (sigpipe, sig_ign); <br/> signal (sigttou, sig_ign ); <br/> signal (sigttin, sig_ign); <br/> signal (sigchld, sig_ign); </P> <p> If (Fork ()> 0) <br/> exit (0); </P> <p> chdir ("/"); <br/> umask (0); <br/>}

 

About zombie processes:

In the fork ()/execve () process, assume that the parent process still exists at the end of the Child process, and the parent process fork () has not installed the sigchld signal processing function to call waitpid () when the sub-process ends and the signal is not explicitly ignored, the sub-process becomes a zombie and cannot end normally. In this case, even the root identity kill-9 cannot kill the zombie process. The remedy is to kill the parent process of the zombie process (the parent process of the zombie process must exist). The zombie process becomes an "orphan process" and passes the process init to process 1, init is always responsible for cleaning up zombie processes.

A zombie process means that the parent process has exited, and the dead process becomes a zombie process without being accepted by the process.
How to generate botnets:
When a process calls the exit command to end its own life, it is not actually destroyed, but it leaves a data structure called Zombie (the system calls exit, it is used to exit a process, but it is only limited to converting a normal process into a zombie process and cannot completely destroy it ). In the Linux Process status, zombie Processes
It has abandoned almost all the memory space, no executable code, and cannot be scheduled. It only keeps a location in the process list, record the rollback of the process
In addition, zombie processes no longer occupy any memory space. It requires its parent process to collect dead parts for it. If the parent process does not have the sigchld message installed
The number processing function calls wait or waitpid () to wait for the sub-process to end, and does not explicitly ignore the signal, it will remain zombie. If the parent process is finished, the INIT process automatically
It will take over the sub-process and collect the corpse for it. It can still be cleared. However, if the parent process is a loop and does not end, the child process will remain zombie, which is why many zombie processes sometimes exist in the system.
How to view botnets:
Using the command ps, we can see that the process marked as Z is a zombie process.
How to clear zombie processes:
1. Rewrite the parent process and send it to the dead after the child process dies. The specific method is to take over the sigchld signal. After a child process dies, it sends a sigchld signal to the parent process. After receiving the signal, the parent process executes the waitpid () function to collect the child process. This is based on the principle that even if the parent process does not call wait, the kernel will send sigchld messages to it, even though the default processing is ignored. If you want to respond to this message, you can set a processing function.
2. Kill the parent process. After the death of the parent process, the zombie process becomes an "orphan process". After it passes through to the INIT process on process 1, init will always be responsible for cleaning up the zombie process. All the zombie processes it generates will also disappear.
========================================================== ===
In Linux
PS auwx
Botnets discovered
A All w/tty, including other users all windows and terminals, including processes of other users
U user-oriented for users (user friendly)
-W, W wide output wide format output
X processes W/O controlling TTYs
It will be marked after the zombie Process
PS axf
View the process tree and list the real processes in a tree
PS axm
The thread is listed. in Linux, the process and thread are unified. They are two lightweight processes.
PS axu
Displays the detailed status of a process.
========================================================== ===
Killall
Kill-15
Kill-9
Generally, defunct processes cannot be killed.
If kill-15 is used, more zombie processes will be generated after kill-9.
Kill-kill PID
Fuser-K PID
You can consider killing the parent process,
Kill-9 his parent process
========================================================== ===
A process that has been terminated but has not been well processed by its parent process (getting information about the final child process and releasing the resources it still occupies) is called a dead process (zombie process ).
To avoid zombie:
1) In svr4, IF signal or sigset is called to set sigchld configuration to ignore, no zombie sub-process will be generated. In addition, you can set the sa_nocldwait flag to prevent sub-processes from freezing.
This function can also be used in Linux. It is called at the beginning of a program.
Signal (sigchld, sig_ign );
2) Call fork twice. The Program 8-5 implements this.
3) Use waitpid to wait for the sub-process to return.
========================================================== ===
Zombie processes are zombie processes. First, it can be prevented by using functions such as wait and waitpid.
The termination status of the process to release resources. The other is fork twice.
========================================================== ===
The defunct process only has a record in the Process Table, and other resources are not occupied. Unless the number of processes in your system exceeds the limit, the zombie process will not have more disadvantages.
The only possible method is that the reboot system can eliminate the zombie process.
========================================================== ===
Any program has a zombie state, which occupies a little memory resources (that is, there is a record in the Process Table). It is just a representation and you don't have to be afraid. If there is a problem with the program, the simple and effective way to solve a large number of botnets is to restart. Kill is ineffective.
Fork and zombie/defunct"
The operating methods of some processes in UNIX. When a process dies, it does not completely disappear. The process is terminated, and it does not run any more, but there are some residual things waiting for the parent process to be withdrawn. These residual things include the returned values of sub-processes and other things. When the parent process fork () is a sub-process, it must use wait () or waitpid () to wait for the sub-process to exit. It is this wait () action that makes the child process residue disappear.
Naturally, there is an exception in addition to the above rules: the parent process can ignore sigcld soft interruptions without wait (). You can do this (on a system that supports it, such as Linux ):
   Main () </P> <p >{</P> <p> signal (sigcld, sig_ign);/* Now I don't have to wait ()! */</P> <p>. </P> <p>. </P> <p> fork ();/* rabbits, rabbits, rabbits! */</P> <p >}< br/>Now, when a child process dies, the parent process does not have wait (). Usually PS shows it as "". It will always remain this way until the parent process wait (), or as follows.
Here is another rule you must know: when the parent process dies before its wait () child process (assuming it does not ignore sigcld), the child process will put Init (PID 1) process as its parent process. This is not a problem if the sub-process works well and can be controlled. However, if the sub-process is already defunct, we will have a little trouble. Look, the original parent process can no longer wait (), because it has vanished. In this way, how does init know the zombie processes such as wait.
Answer: unpredictable. In some systems, init periodically destroys all of its defunct processes. In other systems, it simply rejects the parent processes of any defunct process, but destroys them immediately. If you use one of the above systems, you can write a simple loop and fill the process table with the defunct process that belongs to init. This probably won't make your system administrator very happy, right?
Your task: Make sure that your parent process does not ignore sigcld or wait () It fork () all processes. However, you may not always do this (for example, you want to start a daemon or something else), but you must be careful with programming if you are a newbie to fork. In addition, do not be psychologically bound.
Summary:
The child process becomes defunct until the parent process wait (), unless the parent process ignores sigcld.
Furthermore, the child process (active or defunct) of the parent process that does not have wait () disappears (assuming that the parent process does not ignore sigcld) becomes the child process of init, init processes them in a heavy way. ZT: http://blog.csdn.net/eroswang/archive/2008/11/19/3333617.aspx

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.