【发布时间】:2016-03-21 07:17:38
【问题描述】:
我正在使用 php exec() 运行一个可执行文件,它似乎永远不会结束。
但是在shell中运行这个可执行文件是可以的
这是可执行文件的主要功能:
fork();
子进程会做一些浪费时间的事情。 我 setrlimit 一个 CPU 时间
在父进程中:当计算的used_time超过限制时,监听信号并杀死子进程
如何使 php exec() 工作?
更新:
因为代码太长,我只选了一部分
主函数
child_pid = fork();
if(child_pid == 0)
{
compile();
exit(0);
}
else
{
int res = watch();
if(res)
puts("YES");
else
puts("NO");
}
子进程
LIM.rlim_cur = LIM.rlim_max = COMPILE_TIME;
setrlimit(RLIMIT_CPU,&LIM);
alarm(0);
alarm(LIM.rlim_cur * 10);
switch(language)
{
//..... here is execl() to call compiler like gcc,g++,javac
}
父进程
int status = 0;
int used_time = 0;
struct timeval case_startv, case_nowv;
struct timezone case_startz, case_nowz;
gettimeofday(&case_startv, &case_startz);
while(1)
{
usleep(50000);
kill(child_pid,SIGKILL);
gettimeofday(&case_nowv, &case_nowz);
used_time = case_nowv.tv_sec - case_startv.tv_sec;
if(waitpid(child_pid,&status,WNOHANG) == 0) //still running
{
if(used_time > COMPILE_TIME)
{
report_log("Compile time limit exceed");
kill(child_pid,SIGKILL);
return 0;
}
}
else
{
//handle signals
}
}
为了测试,只需要php文件中的exec()函数
我所说的情况只发生在: 使用 php exec() 运行可执行文件来编译用户代码,如:
#include "/dev/random"
//....
【问题讨论】:
-
代码到底是什么