如何确保PHP实例在后台运行?
我在 MySQL 中有大量行。我将对每一行中的 IP 执行 ping 操作,因此我想拆分负载。我制作了一个脚本,为数据库中的每 100 行运行一个新进程。问题在于,父脚本似乎要等待每个子脚本完成才能开始下一个脚本,这使整个目的无效。
这是父脚本重要部分的代码
for($i = 0; $i < $children_num; $i++)
{
$start = $bn["dots_pr_child"] * $i;
exec("php pingrange.php $i $start $bn[dots_pr_child]");
}
值得一提的是,每个子进程对每个 MySQL 行运行 exec("ping") 一次。我认为这是问题的一部分。
我将根据要求发布更多信息和代码。
有没有办法强制 PHP 实例在后台运行,并让前台继续运行?父脚本最好采用 0.0001 sek 并打印“完成”。目前它运行 120 秒。
感谢您的任何和所有帮助
编辑:我尝试在该过程后添加 &
。人们可能会认为这会让 exec 函数立即返回,但事实并非如此。
编辑:尝试 exec("php pingrange.php $i $start $bn[dots_pr_child] 2>&1 &");
没有成功
编辑:尝试 exec("nohup php pingrange .php $i $start $bn[dots_pr_child] &");
没有成功
I have a ton of rows in MySQL. I'm going to perform a ping on an ip in each of these rows, so I'd like to split the load. I've made a script that runs a new process for every 100 row in the database. The problem is that the parent script seems to wait for each of the child scripts to finish before starting the next one, which voids the entire purpose.
This is the code of the important part of the parent script
for($i = 0; $i < $children_num; $i++)
{
$start = $bn["dots_pr_child"] * $i;
exec("php pingrange.php $i $start $bn[dots_pr_child]");
}
It's worth mentioning that each of these children processes run exec("ping")
once per MySQL row. I'm thinking that's a part of the problem.
I'll post more information and code on request.
Is there a way to force the PHP instance to run in the background, and for the foreground to continue? Preferably the parent script should take 0.0001 sek and print "Done". Currently it runs for 120 seconds.
Thanks for any and all help
Edit: I've tried to add a &
after the process. One would think that'd make the exec function return instantly, but nope.
Edit: Tried exec("php pingrange.php $i $start $bn[dots_pr_child] 2>&1 &");
without success
Edit: Tried exec("nohup php pingrange.php $i $start $bn[dots_pr_child] &");
without success
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
应该在后台完成这项工作。
should do the work in background.
尝试使用
nohup
和 & 符号:维基百科文章nohup 上的 a> 很好地描述了它的作用。
Try
nohup
and the ampersand:The Wikipedia article on
nohup
gives a pretty good description of what it does.虽然对于此特定任务来说可能有些过分,但请考虑 Gearman,这是一个专为您的任务而设计的消息/工作队列做:将任务分包给工人。它具有全面的 PHP 支持。
如果您现在想放弃 Gearman,请查看
proc_open
而不是exec
。它有点复杂,但它为您提供了更高程度的控制,可能更适合您。While it might be overkill for this specific task, consider Gearman, a message / work queue designed for exactly what you're doing: farming out tasks to workers. It has comprehensive PHP support.
If you want to pass on Gearman for now, take a peek at
proc_open
instead ofexec
. It's a bit more complex, but it gives you a higher degree of control that might work better for you.这应该可以工作,因为没有使用默认的 PHP 流。
This should work since none of default PHP streams are used.
只需附加
> /dev/null 2>&1 &
按照您的命令,对我有用。Just append
> /dev/null 2>&1 &
to your command, works for me.