Function name: socket_create_pair()
Applicable version: PHP 4, PHP 5, PHP 7
Function Description: The socket_create_pair() function is used to create a pair of interconnected sockets, which can be used to communicate within the same process.
Syntax: bool socket_create_pair(int $domain, int $type, int $protocol, array &$fd)
parameter:
Return value: Return true if a pair of interconnected sockets are successfully created. If an error occurs, false is returned.
Example:
// 创建一对相互连接的套接字if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $fd) === false) { echo "套接字创建失败: " . socket_strerror(socket_last_error()) . "\n"; exit; } // 在两个套接字之间进行通信$pid = pcntl_fork(); if ($pid == -1) { echo "进程创建失败\n"; exit; } elseif ($pid == 0) { // 子进程$message = "Hello from child process!"; socket_write($fd[0], $message, strlen($message)); exit; } else { // 父进程$message = socket_read($fd[1], 1024); echo "接收到的消息: " . $message . "\n"; pcntl_wait($status); // 等待子进程结束exit; }
In the above example, first, using socket_create_pair() to create a pair of interconnected sockets and store the file descriptors of the two sockets in the $fd array. Then, a child process is created through pcntl_fork(), and the child process sends a message to the parent process. The parent process reads the message sent by the child process through socket_read() and outputs it to the console. Finally, wait for the child process to end through pcntl_wait().