socket_create_pair
創建一對無法區分的套接字並將它們存儲在一個數組中
函數名:socket_create_pair()
適用版本:PHP 4, PHP 5, PHP 7
函數描述:socket_create_pair() 函數用於創建一對相互連接的套接字,這兩個套接字可以用於在同一進程內進行通信。
語法:bool socket_create_pair(int $domain, int $type, int $protocol, array &$fd)
參數:
返回值:如果成功創建了一對相互連接的套接字,則返回true。如果發生錯誤,則返回false。
示例:
// 创建一对相互连接的套接字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; }
以上示例中,首先使用socket_create_pair() 創建了一對相互連接的套接字,並將兩個套接字的文件描述符存儲在$fd 數組中。然後,通過pcntl_fork() 創建了一個子進程,子進程向父進程發送了一條消息。父進程通過socket_read() 讀取子進程發送的消息,並輸出到控制台。最後,通過pcntl_wait() 等待子進程結束。