Php 多进程与多进程通信

版权声明:潘广宇博客, https://blog.csdn.net/panguangyuu/article/details/88375967

一、多进程

<?php

$pid = pcntl_fork();
//父进程和子进程都会执行下面代码
if ($pid == -1) {
    //错误处理:创建子进程失败时返回-1.
     die('could not fork');
} else if ($pid) {
     //父进程会得到子进程号,所以这里是父进程执行的逻辑
     pcntl_wait($status); //等待子进程中断,防止子进程成为僵尸进程。
} else {
     //子进程得到的$pid为0, 所以这里是子进程执行的逻辑。
}

// 等待子进程执行结束
while (pcntl_waitpid(0, $status) != -1) {
    $status = pcntl_wexitstatus($status);
    echo "Child $status completed\n";
}

二、进程间通信

// 创建消息队列

<?php

$msg_key = ftok( __FILE__, 'a' );
$msg_queue = msg_get_queue( $msg_key, 0666 );

//启动进程
$pid = pcntl_fork();

if( $pid == 0 ){
    //子进程向父进程报告
    msg_send( $msg_queue, 1, "father i am " . getmypid(). " and i am working! \n" );
    exit();  //退出子进程
}else if( $pid ){
    msg_receive( $msg_queue, 0, $message_type, 1024, $message, TRUE, MSG_IPC_NOWAIT );
    echo $message;
    pcntl_wait( $status );  //阻塞回收子进程
    if( $status ){
      msg_remove_queue( $msg_queue );
    }
}

猜你喜欢

转载自blog.csdn.net/panguangyuu/article/details/88375967