note 99416 added to function.pcntl-fork
| From: | cmyk777 at gmail dot com | Date: | Mon, 16 Aug 2010 11:41:00 +0000 |
| Subject: | note 99416 added to function.pcntl-fork | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171730@lists.php.net to get a copy of this message | ||
When dealing with fork in a web server environment a bit annoying situation can occur if you are not
waiting for your child processes (for instance you do some long processing in the background) and
you need to return some output to the browser (for example fork result) and finish work with parent.
Your parent is not actually finished (even if you call exit() function), it just returns output to
the web server and waits for a new connection. This behavior leads to a lot of zombie processes in
server's process table, because operating system waits until parent will call wait() function
and get child's exit value. But you are finished your work with parent. It is almost impossible
to call wait() function during next requests to the web server because there is a lot of php-cgi or
forked httpd processes which are not parents of your zombie childs. But we can finish parent right
after the fork. After webserver's process kill, webserver will detect that child is dead and it
will spawn new copy. Tested on Apache prefork and Nginx+spawn_fcgi.
<?php
$pid = pcntl_fork();
if ($pid == -1) {
throw new Exception('could not fork');
} else if ($pid) {
//we are the parent
echo 'Forked successfully';
flush();
//Kill parent process now (self) to prevent zombie creation.
posix_kill(posix_getpid(), SIGTERM);
exit;
} else {
//we are the child
//Do some time-consuming job
//When fork() function is called operating system clones whole process - in case of Apache its
child, in case of CGI SAPI php-cgi process and usual exit don't work and process will stuck in
the memory. But we can kill own process.
//Kill self
posix_kill(posix_getpid(), SIGTERM);
//Usual exit don't work
exit;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 77.68.106.226
----
Manual Page -- http://www.php.net/manual/en/function.pcntl-fork.php
Edit -- https://master.php.net/note/edit/99416
Del: integrated -- https://master.php.net/note/delete/99416/integrated
Del: useless -- https://master.php.net/note/delete/99416/useless
Del: bad code -- https://master.php.net/note/delete/99416/bad+code
Del: spam -- https://master.php.net/note/delete/99416/spam
Del: non-english -- https://master.php.net/note/delete/99416/non-english
Del: in docs -- https://master.php.net/note/delete/99416/in+docs
Del: other reasons-- https://master.php.net/note/delete/99416
Reject -- https://master.php.net/note/reject/99416
Search -- https://master.php.net/manage/user-notes.php