linux下php可以玩玩System v的一系列函数了,尤其感兴趣的是消息队列和信号量,先来用用消息队列.
msg_queque.php
$key = ftok(__FILE__,'a');
//消息队列实例化
$mq = msg_get_queue($key,0666);
for($i=0;$i<10;$i++):
//fork子进程
$pid = pcntl_fork();
if($pid) :
$time = explode(" ",microtime());
//推入队列
msg_send($mq,1,"父进程".posix_getppid()."执行时间:".($time[0]+$time[1]));
elseif($pid == 0) :
$psid = posix_getpid();
$time = explode(" ",microtime());
//推入队列
msg_send($mq,1,"子进程[{$i}]".$psid."执行时间:".($time[0]+$time[1]));
posix_kill($psid,SIGTERM);
endif;
endfor;
do{
//不停的获取消息队列里的消息
msg_receive($mq,0,$msgtye,2048,$message,true,MSG_IPC_NOWAIT);
if(!empty($message)) :
echo $message.PHP_EOL;
endif;
}while(true);
shell下执行php
#php -f msg_queue.php
得到结果
父进程3431执行时间:1315556148.4539
父进程3431执行时间:1315556148.4546
父进程3431执行时间:1315556148.455
父进程3431执行时间:1315556148.4553
父进程3431执行时间:1315556148.4557
父进程3431执行时间:1315556148.456
父进程3431执行时间:1315556148.4564
父进程3431执行时间:1315556148.4568
父进程3431执行时间:1315556148.4572
子进程[5]3644执行时间:1315556148.4575
子进程[4]3643执行时间:1315556148.458
子进程[6]3645执行时间:1315556148.4596
子进程[3]3642执行时间:1315556148.4584
子进程[2]3641执行时间:1315556148.4606
子进程[7]3646执行时间:1315556148.461
子进程[1]3640执行时间:1315556148.4615
子进程[8]3647执行时间:1315556148.462
子进程[0]3639执行时间:1315556148.4624
父进程3431执行时间:1315556148.463
子进程[9]3648执行时间:1315556148.4804
进程们素质很高的进行排队了,他们可以通过消息队列互相通告对方一些东西。
ipcs查看下,发现
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000000 65536 lake 600 393216 2 dest
0x00000000 98305 lake 600 393216 2 dest
0x00000000 131074 lake 600 393216 2 dest
0x00000000 163843 lake 600 393216 2 dest
0x00000000 196612 lake 600 393216 2 dest
0x00000000 229381 lake 600 393216 2 dest
0x00000000 262150 lake 600 393216 2 dest
0x00000000 294919 lake 600 393216 2 dest
0x00000000 327688 lake 600 393216 2 dest
0x00000000 360457 lake 600 393216 2 dest
0x00000000 393226 lake 600 393216 2 dest
0x00000000 425995 lake 600 393216 2 dest
0x00000000 458764 lake 600 393216 2 dest
0x00000000 491533 lake 600 393216 2 dest
0x00000000 524302 lake 600 393216 2 dest
0x00000000 688143 lake 600 393216 2 dest
0x00000000 5177360 lake 600 4 2 dest
0x00000000 5505041 lake 600 4 2 dest
0x00000000 5373970 lake 600 4 2 dest
0x00000000 19103763 lake 600 393216 2 dest
0x00000000 5472276 lake 666 4 2 dest
0x00000000 5275669 lake 666 4 2 dest
0x00000000 5341206 lake 666 4 2 dest
0x00000000 19136535 lake 600 393216 2 dest
0x00000000 1736728 lake 600 393216 2 dest
0x00000000 10190878 lake 600 393216 2 dest
0x00000000 21725226 lake 600 393216 2 dest
0x00000000 21757995 lake 600 393216 2 dest
------ Semaphore Arrays --------
key semid owner perms nsems
0x00000000 0 www-data 600 1
------ Message Queues --------
key msqid owner perms used-bytes messages
0x610845ec 32768 root 666 0 0
三个区间分别是共享内存,信号量,消息队列,ipcrm -q 32768即可清空刚才生成的消息队列。