<?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;
}
}
}