Why there is No Zombie process
-
19-06-2021 - |
Question
As I have not waited for the children process in the following code, but there is no zombie process after running, so why?
In my understanding, zombie process generated in this condition: parent process exits without calling 'wait' or 'waitpid' for its children, so the system process init picks up these children process, which are called zombie process, isn't right?
<?php
define("PC", 10); // Process Count
if (!function_exists('posix_mkfifo')) {
die("posix_mkfifo not existing\n");
}
if (!function_exists('pcntl_fork')) {
die("pcntl_fork not existing");
}
// create pipe
$sPipePath = "my_pipe.".posix_getpid();
if (!posix_mkfifo($sPipePath, 0666)) {
die("create pipe {$sPipePath} error");
}
$arrPID = array();
for ($i = 0; $i < PC; ++$i ) {
$nPID = pcntl_fork(); // create a child process
if ($nPID == 0) {
// children
$oW = fopen($sPipePath, 'w');
fwrite($oW, $i."\n");
fclose($oW);
exit(0); // child end
}elseif($nPID > 0) {
// parent
//array_push($arrPID, $nPID);
//while($pid = pcntl_wait($nStatus, WNOHANG OR WUNTRACED) > 0) {
//echo "$pid exit\n";
//}
}
}
// wait for all child process
//foreach($arrPID as $nPID){
//echo "$nPID\n";
//pcntl_waitpid($nPID, $nStatus); // cause process undead
//pcntl_wait($nStatus);
//}
// parent
$oR = fopen($sPipePath, 'r');
$sData = '';
while(!feof($oR)) {
$sData .= fread($oR, 1024);
}
fclose($oR);
unlink($sPipePath); // remove pipe
//check result
$arr2 = explode("\n", $sData);
$map = array();
foreach($arr2 as $i) {
if (is_numeric(trim($i))) {
$map[trim($i)] = '';
}
}
echo count($map) == PC ? 'ok' : "error count " . count($map);
?>
Solution
They're only zombie processes until their parent either reaps them or dies. Once they've been reparented to init
they are reaped and so no longer exist.
OTHER TIPS
You wrongly understood zombie process.
Flow of process
1.Whenever any child process terminates it send some signal to parent process, and parent process then send request to os to delete process table of that child.
2.Suppose you child process terminates meanwhile time your parent process was in sleep state.So now parent didnt recieve any signal.
3.Now though the child process terminates but it remains and occupy process id as well as space in process table. Now you can say your child process is become zombie.
Practical Scenrio : Every new process is assigned a unique process id. If many zombie process exist it will not allow you to create new process as process ids are limited