stream_socket_pair
Create a pair of exactly the same network socket connection streams
Function name: stream_socket_pair()
Function Description: The stream_socket_pair() function creates a pair of interconnected stream sockets for inter-process communication.
Applicable version: PHP 5 >= 5.1.0, PHP 7
Syntax: stream_socket_pair(int $domain, int $type, int $protocol)
parameter:
Return value:
Example:
// 创建流套接字对$sockets = stream_socket_pair(AF_UNIX, SOCK_STREAM, 0); if ($sockets === false) { echo "创建流套接字对失败"; exit; } // 在父进程中写入数据到套接字$data = "Hello child process!"; fwrite($sockets[0], $data); // 在子进程中读取套接字中的数据$receivedData = fread($sockets[1], strlen($data)); // 输出从父进程传递给子进程的数据echo $receivedData; // 关闭套接字fclose($sockets[0]); fclose($sockets[1]);
In the example above, we first create a convection socket using stream_socket_pair()
function. We then write data to the socket in the parent process and read data from the socket in the child process. Finally, we output the data passed from the parent process to the child process and close the socket.
Note that stream_socket_pair()
function can only be used on socket-enabled operating systems such as Linux or Unix.