Home > Article > Backend Development > Code example of php multi-process processing tcp connection
This article brings you code examples about PHP multi-process processing of TCP connections. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The code is as follows:
<?php if(($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) { echo "failed to create socket: ".socket_strerror($sock)."\n"; exit(); } if(($ret = socket_bind($sock,'127.0.0.1', 8888)) < 0) { echo "failed to bind socket: ".socket_strerror($ret)."\n"; exit(); } if( ( $ret = socket_listen( $sock, 0 ) ) < 0 ) { echo "failed to listen to socket: ".socket_strerror($ret)."\n"; exit(); } while (true) { $conn = @socket_accept($sock); //子进程 if(pcntl_fork() == 0) { $recv = socket_read($conn, 8192); //处理数据 $send_data = "server: ".$recv; socket_write($conn, $send_data); socket_close($conn); exit(0); } else { socket_close($conn); } }
Each connection corresponds to a process, similar to apache's perwork mode
php multi-process explanation
<?php $pid = pcntl_fork(); //父进程和子进程都会执行下面代码 if ($pid == -1) { //错误处理:创建子进程失败时返回-1. die('could not fork'); } else if ($pid) { //父进程会得到子进程号,所以这里是父进程执行的逻辑 pcntl_wait($status); //等待子进程中断,防止子进程成为僵尸进程。 } else { //子进程得到的$pid为0, 所以这里是子进程执行的逻辑。 } ?>
The above is the detailed content of Code example of php multi-process processing tcp connection. For more information, please follow other related articles on the PHP Chinese website!