stream_socket_pair,他的作用是创建一对完全一样的网络套接字连接流 ,通常会被用在进程间的通信具体参数这里不再讲述,文档里都有,我们解释一下文档中的例子
?php
$sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
/* parent */
fclose($sockets[0]);
fwrite($sockets[1], "child PID: $pid\n");
echo fgets($sockets[1]);
fclose($sockets[1]);
} else {
/* child */
fclose($sockets[1]);
fwrite($sockets[0], "message from child\n");
echo fgets($sockets[0]);
fclose($sockets[0]);
}
?>
上面的例子输出如下:
child PID: 1378 message from child
解释下例子
首先执行这段程序的进程先产生一对连接,然后fork一个新的进程,主进程往$socket[1]中写入消息"child PID: $pid\n");
然后子进程会往$sockets[0]中写入消息message from child\n,并读出$socket[1]中的消息,同时主进程也能接受到子进程写入的消息
这样就实现了进程间的通信
另外,产生的这对连接在同一进程下也可以通信
<?php
$sockets = stream_socket_pair ( STREAM_PF_UNIX , STREAM_SOCK_STREAM , STREAM_IPPROTO_IP );
$pid = pcntl_fork ();
if ( $pid == - 1 ) {
die( 'could not fork' );
} else if ( $pid ) {
/* parent */
//fclose ( $sockets [ 0 ]);
fwrite ( $sockets [ 1 ], "child PID: $pid \n" );
fwrite ( $sockets [ 0 ], "message from child\n" );
echo 'main-'.fgets ( $sockets [ 1 ]);
echo 'child-'.fgets ( $sockets [ 0 ]);
fclose ( $sockets [ 0 ]);
fclose ( $sockets [ 1 ]);
}
?>