采用cli的方式運行PHP腳本
STDIN:讀取腳本的輸入字符
<?php
echo "please input a string:";
$stdin=fread(STDIN,65535);
echo "you have input:$stdin";
exit;
從命令行輸入字符,能看到打印出對應的字符慢味;注意fread會阻塞進程场梆,必須輸入之后,程序才會繼續(xù)執(zhí)行
PHP開啟一個子進程
index.php
$child_file = "proc.php";
$descriptorspec = array(
0 => array("pipe", "r"), // 輸入纯路,子進程從此管道中讀取數(shù)據(jù)
1 => array("pipe", "w"), // 輸出或油,子進程輸出
2 => array("file", "error-output.txt", "a") // 標準錯誤,寫入到一個文件
);
$child_process = proc_open("php {$child_file}", $descriptorspec, $pipes);
echo "please input:";
$stdin=fread(STDIN,65535);
echo "you hanve input $stdin";
fwrite($pipes[0], $stdin);
$stdout=fread($pipes[1],65535);
echo "parent recieve : $stdout";
proc_close($child_process);
exit;
proc.php
<?php
$stdin = fread(STDIN, 65535);
sleep(3);
echo "parent process transmit:" . $stdin;
運行index.php驰唬,提示請輸入顶岸,當輸入字符之后,index將輸入的打印出來叫编,等待3秒之后辖佣,proc又將收到的字符返回給index,由index再次打印出來搓逾。效果如圖:
image.png
proc_open($file,$descriptorspec,$pipes)
開啟一個子進程卷谈。
$file:子進程要打開的腳本
$descriptorspec:輸入輸出讀取的配置文件,數(shù)組
$descriptorspec=array(
0 =>input,
// input= array("pipe", "r")則主進程從 $pipes[0]寫入數(shù)據(jù)霞篡,子進程從STDIN中讀取$pipes[0]中的數(shù)據(jù)
//input=STDIN 則子進程從主進程的STDIN中讀取數(shù)據(jù)
輸入世蔗,子進程從此管道中讀取數(shù)據(jù)
1 =>output,
//output= array("pipe", "w") 主進程echo/print_r的內(nèi)容輸出到$pipes[1]中,主進程從$pipes[1]中取數(shù)據(jù)
//output=STDOUT 子進程輸出的數(shù)據(jù)寇损,直接輸出的到父進程的STDOUT中
2 => array("file", "error-output.txt", "a") // 標準錯誤凸郑,寫入到一個文件
);