Skip to content

Instantly share code, notes, and snippets.

@mmohiudd
Created July 31, 2013 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmohiudd/6125753 to your computer and use it in GitHub Desktop.
Save mmohiudd/6125753 to your computer and use it in GitHub Desktop.
sample fork with shared memory
#!/usr/bin/php
<?php
ini_set("error_reporting",E_ALL);
ini_set("display_errors",1);
printf("%s MAIN %s\n\n", getmypid(), date("H:i:s"));
$shm_id = shm_attach(1);
$main_process_id = getmypid();
while(1){
$pid = pcntl_fork();
$status = "STARTED CHILD 1";
if(getmypid() == $main_process_id){
child_1($pid, $status);
}
if ($pid) {
// we are the parent
pcntl_wait($fork_status); //Protect against Zombie children
printf("%s PARENT($pid) %s\n\n", getmypid(), date("H:i:s"));
} else { // we are the child
child_2($status);
exit();
}
}
printf("======== %s ========\n", date("H:i:s"));
function child_1($sibling_pid, &$status){
global $shm_id;
shm_put_var($shm_id, 0, $status);
sleep(2);
printf(" %s CHILD 1 %s\n", getmypid(), date("H:i:s"));
$status = "WOKE UP " . time();
shm_put_var($shm_id, 0, $status);
sleep(2);
posix_kill($sibling_pid, SIGKILL);
}
function child_2(){
global $shm_id;
while(1){
sleep(1);
$status = shm_get_var($shm_id, 0);
echo "[$status] ";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment