Created
September 26, 2011 10:10
-
-
Save anonymous/1241970 to your computer and use it in GitHub Desktop.
phpredis and pcntl_fork()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//if $fork is true, each time daemon got a job, fork a child to handle it | |
$fork = true; | |
$redis = init_redis(); | |
while (true) //loops infinitely | |
{ | |
echo "start loop @ " . date("H:i:s" ,time()) . "\n"; | |
$job = $redis->lPop("queue"); | |
if (!$job) | |
{ | |
sleep(1); | |
continue; | |
} | |
else { | |
if ($fork) | |
{ | |
$redis->rPush("backed", $job); | |
//got job. Now fork one child to handle it | |
$pid = pcntl_fork(); | |
if ($pid == -1) | |
{ | |
die("system cannot pcntl_fork"); | |
} | |
if ($pid) //parent. Wait for the child and continues | |
{ | |
pcntl_wait($status); | |
$exitStatus = pcntl_wexitstatus($status); | |
if($exitStatus !== 0) { | |
//put job back to queue or other stuff | |
} | |
} | |
else //the child | |
{ | |
perform($job); | |
exit(0); | |
} | |
} | |
else | |
perform($job); | |
} | |
} | |
function perform($job) | |
{ | |
echo "got job @ " . date("H:i:s" ,time()) . "\n"; | |
var_dump($job); | |
echo "\n"; | |
} | |
function init_redis() | |
{ | |
define('REDIS_HOST', '127.0.0.1'); | |
define('REDIS_PORT', '6379'); | |
$redis = new Redis(); | |
$redis->connect(REDIS_HOST, REDIS_PORT); | |
return $redis; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$redis = init_redis(); | |
//$count = how many jobs to put | |
$count = count($argv) > 1 ? $argv[1] : 1; | |
for ($i = 0; $i < $count; $i ++) | |
{ | |
//add a timestamp to distinguish | |
$job = array("class" => "foo", "method" => "bar", "params" => array(1,2,4), "ts" => date("H:i:s", time())); | |
$redis->rPush("queue", json_encode($job)); | |
} | |
$items = $redis->lRange("queue", 0, -1); | |
var_dump($items); //var dump to make sure we see the items successfully pushed in | |
function init_redis() | |
{ | |
define('REDIS_HOST', '127.0.0.1'); | |
define('REDIS_PORT', '6379'); | |
$redis = new Redis(); | |
$redis->connect(REDIS_HOST, REDIS_PORT); | |
return $redis; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment