PHP多进程DEMO

php

浏览数:289

2019-1-7


PHP多进程DEMO

<?php
declare( ticks=1 );

pcntl_signal( SIGCHLD, "sig_handler" );
function sig_handler( $signo ) {
    switch ( $signo ) {
        case SIGCHLD:
            $status   = 0;
            $child_id = pcntl_wait( $status );
            echo sprintf( "child exit id: {$child_id} \n" );
//          exit( 0 );
            break;

        default:
            echo 'uncaugh signal !';
    }

}

$i   = 0;
$pid = pcntl_fork();
if ( $pid > 0 ) {
    echo "我是parent \n";
    while ( 1 ) {
        $i ++;
        sleep( 1 );
        echo "父进程" . $i . PHP_EOL;
        if ( $i > 20 ) {
            break;
        }
    }
    $name = "小头爸爸";
} elseif ( $pid == - 1 ) {
    die( 'fork error' );
} else {
    echo "child begin \n";
    //子进程得到的$pid为0, 所以这里是子进程执行的逻辑。
    while ( 1 ) {
        $i ++;
        sleep( 1 );
        echo '子进程' . $i . PHP_EOL;
        if ( $i > 10 ) {
            echo "child exit \n";
            exit( 0 );
        }
    }
    $name = "大头儿子";
}

var_dump( $name );