php多進程實現
PHP有一組進程控制函數(編譯時需要–enable-pcntl與posix擴展),使得php能在nginx系統中實現跟c一樣的創建子進程、使用exec函數執行程序、處理信號等功能。
CentOS 6 下yum安裝php的,默認是不安裝pcntl的,因此需要單獨編譯安裝,首先下載對應版本的php,解壓后
1
2
3
4
5
6
|
cd php-version/ext/pcntl phpize ./configure && make && make install cp /usr/lib/php/modules/pcntl.so /usr/lib64/php/modules/pcntl.so echo "extension=pcntl.so" >> /etc/php.ini /etc/init.d/httpd restart |
方便極了。
下面是示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
<?php header( 'content-type:text/html;charset=utf-8' ); // 必須加載擴展 if (!function_exists( "pcntl_fork" )) { die ( "pcntl extention is must !" ); } //總進程的數量 $totals = 3; // 執行的腳本數量 $cmdArr = array (); // 執行的腳本數量的數組 for ( $i = 0; $i < $totals ; $i ++) { $cmdArr [] = array ( "path" => __DIR__ . "/run.php" , 'pid' => $i , 'total' => $totals ); } /* 展開:$cmdArr Array ( [0] => Array ( [path] => /var/www/html/company/pcntl/run.php [pid] => 0 [total] => 3 ) [1] => Array ( [path] => /var/www/html/company/pcntl/run.php [pid] => 1 [total] => 3 ) [2] => Array ( [path] => /var/www/html/company/pcntl/run.php [pid] => 2 [total] => 3 ) ) */ pcntl_signal(SIGCHLD, SIG_IGN); //如果父進程不關心子進程什么時候結束,子進程結束后,內核會回收。 foreach ( $cmdArr as $cmd ) { $pid = pcntl_fork(); //創建子進程 //父進程和子進程都會執行下面代碼 if ( $pid == -1) { //錯誤處理:創建子進程失敗時返回-1. die ( 'could not fork' ); } else if ( $pid ) { //父進程會得到子進程號,所以這里是父進程執行的邏輯 //如果不需要阻塞進程,而又想得到子進程的退出狀態,則可以注釋掉pcntl_wait($status)語句,或寫成: pcntl_wait( $status ,WNOHANG); //等待子進程中斷,防止子進程成為僵尸進程。 } else { //子進程得到的$pid為0, 所以這里是子進程執行的邏輯。 $path = $cmd [ "path" ]; $pid = $cmd [ 'pid' ] ; $total = $cmd [ 'total' ] ; echo exec ( "/usr/bin/php {$path} {$pid} {$total}" ). "\n" ; exit (0) ; } } ?> |
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://blog.csdn.net/e421083458/article/details/22186475