php 后台运行函数,如何在主线程分开的后台运行php函数?

本文探讨了如何在PHP中使用exec函数实现长时间运行的函数异步执行,以及如何通过fork()方法将任务放到子进程进行,避免阻塞用户界面。还提供了两种解决方案,包括直接fork()和使用ob_start()捕获输出,以实现在后台运行wiki.php更新_wiki函数并保存输出到文件。
摘要由CSDN通过智能技术生成

所以我有一个主要的PHP线程,我想在其中调用一个函数,使其在后台运行并且不会让用户等待,因为这个函数需要很长时间才能执行.

$logFile = 'app-output.txt';

$command = 'nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);" &';

$command.= ' > "'.$logFile.'" 2>&1';

exec($command);

所以我尝试使用exec函数,但由于某种原因它不会在后台运行.

wiki.php是一个具有update_wiki功能的文件需要很长时间,所以我想将用户重定向到他来自的页面,而这个功能完成它的工作,因为它无论如何独立并将输出转储到其他地方

解决方法:

这是fork的示例方法:

$logFile = 'app-output.txt';

$command = 'nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);" &';

$command.= ' > "'.$logFile.'" 2>&1';

$pid = pcntl_fork();

if ($pid == -1) {

die('could not fork');

} else if ($pid) {

// we are the parent, do nothing

} else {

// we are the child

exec($command);

}

另一种方法可以是:

$pid = pcntl_fork();

if ($pid == -1) {

die('could not fork');

} else if ($pid) {

// we are the parent, do nothing

} else {

// we are the child

$logFile = 'app-output.txt';

ob_start();

require '/export/wiki.php';

update_wiki(1);

file_put_contents($logFile, ob_get_contents());

}

标签:php,exec

来源: https://codeday.me/bug/20190830/1769696.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值