note 36603 added to ref.pcntl
| From: | jeremy at nirvani dot net | Date: | Thu, 16 Oct 2003 00:54:22 +0000 |
| Subject: | note 36603 added to ref.pcntl | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-58671@lists.php.net to get a copy of this message | ||
#!/usr/local/bin/php -q
<?php
# Jeremy Brand <jeremy@nirvani.net>
# http://www.nirvani.net/
# ./configure --enable-pcntl --enable-sigchild
# make
# make install
# This code example shows how to use a script to do multiprocessing. Each time
# this script is ran, the result is 5 (in this example) processes running to
# accomplish a specified task.
# Examples could be a messaging queue. You could get the number of messages in
# a queue and handle any or all of them asynchronously.
# Get the number of children you want to be born by running this
# script once.
$children = 5; # likely a function call here.
for ($i=1; $i<=$children; $i++)
{
$pid = pcntl_fork();
if ($pid == -1)
{
die("could not fork\n");
}
else if ($pid)
{
# If we are the parent, we did our job of giving birth,
# now lets finish our job and die!
exit(0);
}
else
{
# Since we are the child, fork so that init will become our parent. Init
# is good at wait()ing on children - ie: reaping.
$cpid = pcntl_fork();
if ($cpid == -1)
{
die("could not fork in child process\n");
}
if (!$cpid)
{
# We have now forked off from our parent and also are not waiting on any
# other children to process, however other children are running
# simutaniously to us. Make sure the code you write here is safe to run
# in this environment of multiprocessing - ie: proper locking, etc.
# Write the custom code here that you want to multiprocess.
# ADD CODE HERE TO MULTIPROCESS
print "we are child number $i\n";
# Don't forget to exit after the child processing is done. Certainly
# change this exit code if you need to however.
exit(0);
}
}
}
?>
----
Manual Page -- http://www.php.net/manual/en/ref.pcntl.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+36603
Delete -- http://master.php.net/manage/user-notes.php?action=delete+36603&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+36603&report=yes
Search -- http://master.php.net/manage/user-notes.php