简体   繁体   English

如何强制调用`exec()`的时间限制?

[英]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);

You can probably use ulimit for that: 您可以使用ulimit

exec(" ( ulimit -t 1 ; gcc ... | /var/www/binary) ");

That of course only works if the process uses active CPU time, not if it waits for I/O endlessly. 这当然只有在进程使用活动CPU时间时才有效,而不是无休止地等待I / O.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM