toxic

备忘录

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
<?php
/**
 * Created by PhpStorm.
 * User: lost
 * Date: 14-2-10
 * Time: 上午10:51
 * fork 中必须以cli 命令行方式运行 以web 形式运行的化 只能运行父进程
 * 例如
 *  /usr/local/php/bin/php  /Users/lost/www-nginx/libevent/fork.php
 *
 * 用过的chr()函数,(这是一个把输入的ASCII数字码转义为对应的ASCII字符的函数,在某些特殊字符被过滤的时候,尤其有用)
 * 命令行下用chr(10) 换行
 */

    print 'parent pid is:'.getmypid().chr(10);

    $pid = pcntl_fork();
    if($pid > 0){//父进程
        print  'im parent and child pid is :'.$pid.chr(10);
    }
    else if($pid == -1){
        print 'could not fork';
    }else{//子进程
        print 'im child and my pid is:'.getmypid().chr(10);
    }



 例子2:

//创建3个子进程
$pids = array();//子进程的进程号
$pid = pcntl_fork();
for($i =0 ; $i < 3 ; $i++){
    if($pid == -1){
        print "不能创建子进程".chr(10);
    }else if($pid){
        //父进程里$pid为子进程的进程号
        //print '子进程号:'.$pid.chr(10);
        print '父进程号:'.getmypid().chr(10);
        $pid = pcntl_fork();
        $pids[] = $pid;
    }else{
        print '子进程号:'.getmypid().chr(10);
    }
}

输出为:

父进程号:4677
子进程号:4678
子进程号:4678
子进程号:4678
父进程号:4677
子进程号:4679
子进程号:4679
父进程号:4677
子进程号:4680

 

 

根据例子2 如果分别想在子进程里做不同的事情//创建3个子进程

$pids = array();//子进程的进程号
$excutable = array(
    'test1' => true,
    'test2' => true,
    'test3' => true
);
$pid = pcntl_fork();
for($i =1 ; $i < 4 ; $i++){ if($pid == -1){ print "不能创建子进程".chr(10); }else if($pid){ //父进程里$pid为子进程的进程号 //print '子进程号:'.$pid.chr(10); print '父进程号:'.getmypid().chr(10); $pid = pcntl_fork(); $pids[] = $pid; }else{ print '子进程号:'.getmypid().chr(10); //在子进程里执行函数test1,2,3 $function_name = 'test'.$i; if($excutable[$function_name]) eval($function_name.'();'); } } function test1(){ global $excutable; $excutable[__FUNCTION__] = false; while(1){ print 'test1:method execute'.chr(10); sleep(5); } } function test2(){ global $excutable; $excutable[__FUNCTION__] = false; while(1){ print 'test2:method execute'.chr(10); sleep(5); } } function test3(){ global $excutable; $excutable[__FUNCTION__] = false; while(1){ print 'test3:method execute'.chr(10); sleep(5); } }





输出结果为:

父进程号:4819
子进程号:4820
test1:method execute
父进程号:4819
子进程号:4821
父进程号:4819
test2:method execute
子进程号:4822
test3:method execute

 
//每5秒会输出

test1:method execute

test2:method execute
test3:method execute



 根据上面的代码 得到最后一种 (假如在子进程执行第一次完毕后就把他kill掉的话就完美的实现了每次循环父进程只会分配一个子进程而不会让子进程再次循环生成仔仔进程)

//创建3个子进程
$pids = array();//子进程的进程号
for($i =0 ; $i < 3 ; $i++){
    $pids[$i] = pcntl_fork();
    if($pids[$i] == -1){
        print "不能创建子进程".chr(10);
    }else if($pids[$i]){
        pcntl_wait($status);//如果需要同时进行多个进程 请注释此行 因为会导致父进程阻塞
    }elseif($pids[$i] == 0){
        $pid = getmypid();
        print '子进程号:'.getmypid().chr(10);
        posix_kill($pid, SIGTERM);//杀掉子进程 防止子进程再生成子进程
    }
}


结果:
子进程号:5754
子进程号:5755
子进程号:5756

 

posted on 2014-02-10 11:50  toxic  阅读(249)  评论(0编辑  收藏  举报