php multiple processes - Notes

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/raoxiaoya/article/details/100555418

php multiple processes - Notes

1, the output of the child process will be output by the parent process.
2, pcntl_wait () and pcntl_waitpid () function call wait method operating system, is a blocking operation.
3, the parent process must wait for the child before quitting.
4, if multiple children, you will need a while loop to wait, because as long as there is a child process exits the triggers pcntl_wait execution.
5, the child process can inherit by way of inheritance context connection handle of the parent process, to do some of the operations while the child and the parent can release
or destroy the connection. Moreover, once the parent / child process exits default will release all of the handle.

<?php

$mysqli = new mysqli('127.0.0.1', 'root', 'Rxy123**', 'data', 3306);

if($mysqli->connect_error){
	die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

$pid = pcntl_fork();
if($pid == -1){

    echo 'fork error'.PHP_EOL;
}elseif($pid){

    echo 'this is father '.posix_getpid().PHP_EOL;
}else{

    $re = $mysqli->query("insert into member(name,age,time) values('ddd', 23, ".time().")");
    var_dump($re);// 打印在父进程
    sleep(3);// 核实 pcntl_wait 是否会阻塞
    echo 'this is son '.posix_getpid().PHP_EOL;
}

// 阻塞
$nPID = pcntl_wait($nStatus);
if ($nPID > 0) {
    echo "{$nPID} exit\n";
}

// $mysqli 已经被子进程释放了,所以这里会报错 MySQL server has gone away
$ret = $mysqli->query('select * from member');
var_dump($ret);

Guess you like

Origin blog.csdn.net/raoxiaoya/article/details/100555418