[英]How can I enforce a time limit on a call to `exec()`?
I'm trying to make an online judge written PHP. 我正在尝试用PHP编写在线评判。 My code currently looks like:
我的代码目前看起来像:
exec("gcc /var/www/qwerty.c -o /var/www/binary",$output,$returnval);
print_r($output);
exec("cat /var/www/qwe.txt | /var/www/binary",$output,$returnval);
print_r($output);
However, I want each process spawned by exec
to have at most 1 second to run. 但是,我希望
exec
生成的每个进程最多运行1秒。 I'm not sure how to do this. 我不知道该怎么做。 set_time_limit() isn't working
set_time_limit()不起作用
I would use the proc_
functions as suggested by @Adam Wright, but a quick alternative to Linux-like environments is to use the GNU timeout
command before your command: 我会使用@Adam Wright建议的
proc_
函数,但是类似Linux环境的快速替代方法是在命令之前使用GNU timeout
命令:
// If it took more than 1 second, $returnval will got the exit code 124
exec('timeout 1 gcc /var/www/qwerty.c -o /var/www/binary', $output, $returnval);
This can be achieved using the proc_
family of functions. 这可以使用
proc_
系列函数来实现。 Launch your processes using proc_open
. 使用
proc_open
启动流程。 Repeatedly poll using proc_status
(with some small sleep in-between polls) until either the process has returned or 1 second has passed. 使用
proc_status
(在proc_status
轮询之间进行一些小的睡眠)重复轮询,直到进程返回或已经过了1秒。 If 1 second passes without proc_status
indicating the process has finished, use proc_terminate
(or proc_close
) to kill it off, and take appropriate action. 如果1秒没有
proc_status
指示进程已完成,则使用proc_terminate
(或proc_close
)将其proc_close
,并采取适当的操作。
I'm not saying that spawning external processes in a PHP script is a good idea, though. 我并不是说在PHP脚本中生成外部进程是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.