【问题标题】:php exec() never endedphp exec() 从未结束
【发布时间】: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"
    //....

【问题讨论】:

  • 代码到底是什么

标签: php exec


【解决方案1】:

服务器上的 PHP 脚本执行时间有限。以这种方式执行长时间运行的脚本通常不是一个好主意。建议将它们作为后台作业运行。

这是在 php.ini 中定义的,对于 apache 和 shell 是不同的

【讨论】:

  • 我想写这个答案来要求更多的澄清,因为我不能评论@Wumpus
【解决方案2】:

终于知道为什么会这样了..

我只是杀死 childpid 而不是杀死由 childpid 引起的其他进程

所以 php exec() 会一直运行

【讨论】:

    猜你喜欢
    • 2011-01-25
    • 2021-06-02
    • 2011-09-08
    • 1970-01-01
    • 2012-02-03
    • 2012-02-21
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多