1. 程式人生 > >php 多程序程式設計

php 多程序程式設計

第一步:

$ php -m  命令檢視php是否安裝pcntl 和 posix擴充套件,若沒有則安裝

使用場景:

1. 要進行大量的網路耗時的操作

2. 要做大量的運算,並且,系統有多個cpu,為了讓使用者有更快的體驗,把一個任務,分成幾個小任務,最後合併。

多程序常用函式:

pcntl_alarm — 為程序設定一個alarm鬧鐘訊號
pcntl_errno — 別名 pcntl_strerror
pcntl_exec — 在當前程序空間執行指定程式
pcntl_fork — 建立子程序,在當前程序當前位置產生分支(子程序)。譯註:fork是建立了一個子程序,父程序和子程序 都從fork的位置開始向下繼續執行,不同的是父程序執行過程中,得到的fork返回值為子程序 號,而子程序得到的是0
。 pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed pcntl_getpriority — 獲取任意程序的優先順序 pcntl_setpriority — 修改任意程序的優先順序 pcntl_signal_dispatch — 呼叫等待訊號的處理器 pcntl_signal — 安裝一個訊號處理器 pcntl_sigprocmask — 設定或檢索阻塞訊號 pcntl_sigtimedwait — 帶超時機制的訊號等待 pcntl_sigwaitinfo — 等待訊號 pcntl_strerror — Retrieve the
system error message associated with the given errno pcntl_wait — 等待或返回fork的子程序狀態 pcntl_waitpid — 等待或返回fork的子程序狀態 pcntl_wexitstatus — 返回一箇中斷的子程序的返回程式碼 pcntl_wifexited — 檢查狀態程式碼是否代表一個正常的退出。 pcntl_wifsignaled — 檢查子程序狀態碼是否代表由於某個訊號而中斷 pcntl_wifstopped — 檢查子程序當前是否已經停止 pcntl_wstopsig — 返回導致子程序停止的訊號 pcntl_wtermsig — 返回導致子程序中斷的訊號

例項一:

<?php
//最早的程序,也是父程序
$parentPid = getmypid();
echo '原始父程序:' . $parentPid . PHP_EOL;
//建立子程序,返回子程序id
$pid = pcntl_fork();

if( $pid == -1 ){
    exit("fork error");
}
//pcntl_fork 後,父程序返回子程序id,子程序返回0
echo 'ID : ' . $pid . PHP_EOL;

if( $pid == 0 ){
    //子程序執行pcntl_fork的時候,pid總是0,並且不會再fork出新的程序
    $mypid = getmypid(); // 用getmypid()函式獲取當前程序的PID
    echo 'I am child process. My PID is ' . $mypid . ' and my fathers PID is ' . $parentPid . PHP_EOL;
} else {
    //父程序fork之後,返回的就是子程序的pid號,pid不為0
    echo 'Oh my god! I am a father now! My childs PID is ' . $pid . ' and mine is ' . $parentPid . PHP_EOL;
}


$aa = shell_exec("ps -af | grep index.php");
echo $aa;

例項二:開多個子程序,避免fork氾濫

<?php
//最早的程序,也是父程序
$parentPid = getmypid();
echo '原始父程序:' . $parentPid . PHP_EOL;

//開啟十個子程序
for($i = 0; $i < 10; $i++) {
    $pid = pcntl_fork();
    if($pid  == -1) {
        echo "Could not fork!\n";
        exit(1);
    }
    //子程序
    if(!$pid) {
        //child process workspace
        echo '子程序:' . getmypid() . PHP_EOL;
        exit(); //子程序邏輯執行完後,馬上退出,以免往下走再fork子程序,不好控制    
    } else {
        echo '父程序:' . getmypid() . PHP_EOL;
    }
}

echo getmypid() . PHP_EOL;
$aa = shell_exec("ps -af | grep index.php");
echo $aa;

注意:

通過pcntl_XXX系列函式使用多程序功能。注意:pcntl_XXX只能執行在php CLI(命令列)環境下,在web伺服器環境下,會出現無法預期的結果,請慎用!