用文件实现计算器要求多进程同时写

用文件实现一个计算器,要求可满足多进程同时写,最后得出结果。以下为代码:

<?php
$path = 'board.txt';
touch($path);
$max = isset($argv[1]) ? $argv[1] : 100;
for($i = 0;$i < $max;$i++) {
    $pids[$i] = pcntl_fork();
    if($pids[$i] > 0) {
    } else if($pids[$i] == 0) {
        while(1) {
            $fp = fopen($path,'r+');
            if($fp) {
                $lock = flock($fp,LOCK_EX);
                if($lock) {
                    $num1 = fread($fp,4096);
                    $num2 = intval($num1) + 1;
                    fseek($fp,0,SEEK_SET);
                    fwrite($fp,$num2);
                    flock($fp,LOCK_UN);
                    fclose($fp);
                    break;
                }
                fclose($fp);
            }
        }
        exit(0);
    } else {
        echo "fail to fork a pid\n";
    }
}

while(count($pids) > 0) {
    foreach($pids as $key => $pid) {
        $res = pcntl_waitpid($pid, $status, WNOHANG);
        // If the process has already exited
        if($res == -1 || $res > 0)
            unset($pids[$key]);
    }
    sleep(1);
}
$result = file_get_contents($path);
echo 'result is : ',$result,"\n";
unlink($path);

 

posted @ 2015-08-05 15:57  lrxing  阅读(345)  评论(0编辑  收藏  举报