PHP 异步执行 程序、代码、命令[兼容windows、linux]

 1 <?php
 2 echo '<pre>';
 3 $start = microtime(true);
 4 
 5 function execInBackground($cmd)
 6 {
 7 
 8     if (substr(php_uname(), 0, 7) == "Windows") {
 9 
10         pclose(popen("start /B ".$cmd, "r"));
11     } else {
12 
13         exec($cmd . " > /dev/null &");
14     }
15 }
16 // execInBackground("php test2.php -a 333");
17 for($i = 0; $i < 99; $i ++){
18     // 输出文件 ./output.txt 获取错误 2>&1 后台执行 &
19     execInBackground("php test2.php -a ".$i." >>./output.txt 2>&1 &");
20 }
21 
22 $end = microtime(true);
23 $time = $end - $start;
24 
25 //精确到十位小数,可自行调节
26 
27 dump(number_format($time, 10, '.', '') . " seconds");

转自:https://exp.newsmth.net/topic/b1c1b0070bd2c81a5587d920276da64e

kangmingxuan
飞扬 03月17日

这个在PHP的官方文档上有个很好的示例,Windows和Linux都可以:

[code=php]

<?php

function execInBackground($cmd) {

if (substr(php_uname(), 0, 7) == "Windows"){

pclose(popen("start /B ". $cmd, "r"));

}

else {

exec($cmd . " > /dev/null &");

}

}

?>

[/code]

上面回答不可以的,只是他自己不会。作为成熟稳定的操作系统,大多数问题在各个平台上都有解决办法,只是各个平台有所不同而已。

参考:http://php.net/manual/en/function.exec.php

posted @ 2019-06-26 17:36  夏秋初  阅读(785)  评论(0编辑  收藏  举报