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 @   夏秋初  阅读(830)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示