note 33035 added to ref.pcntl

From: Date: Sat, 14 Jun 2003 18:11:18 +0000
Subject: note 33035 added to ref.pcntl
Groups: php.notes 
Request: Send a blank email to php-notes+get-50346@lists.php.net to get a copy of this message
So, you want to create multiple child processes and don't want any zombies, don't you? You can use IPC to achieve just that. Every child that is spawned has to tell its parent that time has come for him to be terminated. So, yes, zombies will be created, but once in a while the parent will 'clean up' after his kids. Code: <?php declare(ticks = 1); // create a IPC message queue $msgqueue = msg_get_queue(ftok("/tmp/php_msgqueue.stat", 'R'),0666 | IPC_CREAT); // loop for 1000 children for ($c = 0; $c < 1000; $c++) { // fork $pcid = pcntl_fork(); if ($pcid == -1) { die("Could not fork!"); } elseif ($pcid) { // we are the parent, look for zombie kids and terminate 'em // look in the IPC message queue if there are any entries $currentqueue = msg_stat_queue($msgqueue); $n = $currentqueue['msg_qnum']; // number of messages (number of kids to terminate) if ($n > 0) { echo "There are $n kids to terminate.\n"; for ($i = 0; $i < $n; $i++) { // pop the kid's PID from the IPC message queue if (!msg_receive ($msgqueue, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) { echo "MSG_RECV ERROR: $errmsg \n"; // something has gone wrong } else { pcntl_waitpid($msg, $tmpstat, 0); // terminate kid for real. }; }; }; } else { // we are the child! if (!posix_setsid()) { die ("Could not detach"); }; // detach echo "I am child number $c\n"; sleep(5); // do something useful // tell dad I'm finished via IPC: send him my PID if (!msg_send($msgqueue, 1, posix_getpid(), true, true, $errmsg)) { echo "MSG_SEND ERROR: $errmsg \n"; }; exit(); // become a zombie until dad kills me }; }; ?> ---- Manual Page -- http://www.php.net/manual/en/ref.pcntl.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33035 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33035&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33035&report=yes

« previous php.notes (#50346) next »