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

时间:2012-02-03 12:50:42

标签: php linux

我正在尝试用PHP编写在线评判。我的代码目前看起来像:

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);

但是,我希望exec生成的每个进程最多运行1秒。我不知道该怎么做。 set_time_limit()无法正常工作

3 个答案:

答案 0 :(得分:6)

我会使用@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);

答案 1 :(得分:4)

您可以使用ulimit

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

当然,只有当进程使用活动的CPU时间时,才会有效,而不是无休止地等待I / O.

答案 2 :(得分:3)

这可以使用proc_系列函数来实现。使用proc_open启动您的流程。使用proc_status(在两次调查之间进行一些小的睡眠)重复轮询,直到进程返回或已经过了1秒。如果1秒没有proc_status表示流程已完成,请使用proc_terminate(或proc_close)将其删除,并采取相应措施。

我并不是说在PHP脚本中生成外部进程是一个好主意。