<?php

/

Copyright (C) Iamasb

共享内存php59php应用旌旗灯号量共享内存实现过程间通讯 AJAX

@project : 3、workerman干系知识点

@explain : 进程间通信-旗子暗记量+共享内存

多进程-通过行列步队

创建两个子进程-卖力对共享内容进行写操作

主进程卖力检测子进程状态

@filename : 32、进程间通信-旗子暗记量+共享内存.php

@author : xiaobei 2801616735@qq.com

/

$key = ftok(__FILE__,'m');

$semId = sem_get($key);

$shmId = shm_attach($key);

define('KEY',1);

/

累加1

先获取信号量

再操作共享内存

/

function toDo()

{

global $semId,$shmId;

if (!sem_acquire($semId)) {

echo 'get sem is error';

exit;

}

if (shm_has_var($shmId,KEY)) {

$value = shm_get_var($shmId,KEY);

echo \"大众value is \"大众,$value,PHP_EOL;

$value++;

shm_put_var($shmId,KEY,$value);

} else {

shm_put_var($shmId,KEY,1);

echo \"大众value is 0\公众,PHP_EOL;

}

sem_release($semId);

exit;

}

function forkPorcess($callBack)

{

$pid = pcntl_fork();

if ($pid<0) {

echo 'fork is error.';

} elseif ($pid>0) {

return $pid;

}

$callBack();

}

for ($i=0;$i<3;$i++) {

$pid = forkPorcess('toDo');

$pidArr[$pid] = $pid;

}

print_r($pidArr);

while (1) {

$pid = pcntl_wait($status,WUNTRACED);

if (isset($pidArr[$pid])) {

echo $pid,' is over.',PHP_EOL;

unset($pidArr[$pid]);

} else {

echo \"大众master is over.\公众;

break;

}

}

// 移除旗子暗记量

sem_remove($semId);

// 移除共享内存数据

shm_remove($shmId);

// 断开共享内存

shm_detach($shmId);

2.2、实行结果