php多进程实践
1. 直接方式pcntl_fork() 创建一个进程,在父进程返回值是子进程的pid,在子进程返回值是0,-1表示创建进程失败。跟c非常相似。
测试脚本 test.php
// example of multiple processes date_default_timezone_set( 'asia/chongqing'); echo parent start, pid , getmypid(), \n ; beep(); for ($i=0; $i 0){ echo parent continue \n; for ($k=0; $k<2; ++$k){ beep(); } } else if ($pid == 0){ echo child start, pid , getmypid(), \n ; for ($j=0; $j 0){ echo parent continue \n; pcntl_wait($status); for ($k=0; $k $task){ if (curl_error($ch[$j])){ echo task ${j} [$task ] error , curl_error($ch[$j]), \r\n ; } else { echo task ${j} [$task ] get: \r\n , curl_multi_getcontent($ch[$j]), \r\n ; } }
编写脚本 test2.php
date_default_timezone_set( 'asia/chongqing'); echo child start, pid , getmypid(), \r\n ; for ($i=0; $i<5; ++$i){ beep(); } exit (0); // *** function beep(){ echo getmypid(), \t , date('y-m-d h:i:s' , time()), \r\n; sleep(1); }
用命令行运行
#php -f test1.php &
输出结果
task 0 [http://localhost/feedbowl/t2.php?job=task1] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39
task 1 [http://localhost/feedbowl/t2.php?job=task2] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39
task 2 [http://localhost/feedbowl/t2.php?job=task3] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39
从打印的时间看到,多个任务几乎是同时运行的。