<?php
$fifoPath ='/tmp/testfifo';
function writedata($data)
{
printf("this is child start");
file_put_contents("/tmp/testdata",FILE_APPEND);
printf("this is child end");
}
while(1)
{
if($argv[1]==1)
{
printf("this is cycle task\r\n");
sleep(60);
continue;
}
// immediate
$fd = fopen($fifoPath, 'r');
// 定义为非阻塞模式.
stream_set_blocking($fd,false);
$readers = array($fd);
$bytes = 4;
$write = NULL;
$except = NULL;
// 需要区分类型的.
while(stream_select($readers, $write, $except, 0, 15) == 1) {
$data = fread($fd, $bytes);
if($data)
{
printf("recv data:%d\r\n",$data);
$pid = pcntl_fork();
//父进程和子进程都会执行下面代码
if ($pid == -1) {
//错误处理:创建子进程失败时返回-1.
printf('could not fork\r\n');
} else if ($pid) {
//父进程会得到子进程号,所以这里是父进程执行的逻辑
printf("this is parent process\r\n");
pcntl_wait($status); //等待子进程中断,防止子进程成为僵尸进程。
} else {
//子进程得到的$pid为0, 所以这里是子进程执行的逻辑。
printf("this is child process\r\n");
writedata($data);
exit(0);
}
sleep(1);
}else{
printf("this is read 0 bytes\r\n");
sleep(1);
continue;
}
}
}