1. 程式人生 > >php+Socket多程序處理速學:防止子程序無限增加

php+Socket多程序處理速學:防止子程序無限增加

<?php $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); socket_bind($socket,'127.0.0.1',9090) or die('error'); socket_listen($socket,5); $child = 0; //初始化子程序數 while(true){ $client = socket_accept($socket); $pid = pcntl_fork(); if ($pid == -1) { die('could not fork'); } else
if ($pid) { socket_close($client); $child++; if($child >= 3){ //假設最大程序數為3 pcntl_wait($status); //等待上一個程序結束 $child--; } } else { $buf = socket_read($client,1024); echo $buf; if(preg_match('/sleep/i',$buf)){ sleep(10
); $html = 'HTTP/1.1 200 OK'.PHP_EOL .'Content-Type: text/html;charset=utf-8'.PHP_EOL.PHP_EOL; socket_write($client,$html); socket_write($client,"this is server,休克了10秒,模擬很繁忙的樣子"); }else{ socket_write($client,"this is server"); } socket_close($client
); exit;//關閉子程序 } } socket_close($socket);