c - 等待子进程的时间不超过 X 秒



我想fork()一个子进程,然后调用execl()将子进程映像替换为可能不会停止的新进程(会卡在while循环中,或者期望输入不应该的地方)。
我想等待它不超过 X 秒。
它应该看起来像这样:

int main() {
    pid_t pid=fork();
    if (pid==-1) {
        perror("fork() error");
    }
    else if (pid==0) {
        //call execlp("exe.out","exe.out",arg1, ... ,NULL)
        //where exe.out might not stop at all
    }
    else {
        //wait for X seconods, and if child process didn't terminate
        //after X seconds have passed, terminate it
    }
}

wait() 和 waitpid() 不提供此功能。
怎么能做到呢?

谢谢!

您可以将信号处理程序警报设置为在 X 秒后响起,然后执行等待(2)。如果等待返回,则子状态在 X 秒之前更改。如果信号处理程序返回,则不会更改子状态。

不要忘记

在等待(2)返回时重置警报。

如果进程没有

从父进程收到pid进程在超时之前结束的信号,则可以再创建一个终止进程pid子进程:

in_, out = pipe()
pid2 = fork()
if pid2 != 0: # parent
   close(in_)
   waitpid(pid, 0) # wait for child to complete
   write(out, b'1') # signal to pid2 child to abort the killing
   waitpid(pid2, 0)
else: # child
   close(out)
   ready, _, _ = select([in_], [], [], timeout) # wait `timeout` seconds
   if not ready: # timeout
      kill(pid, SIGTERM)
      write(2, b"kill child")
   else:
      write(2, b"child ended before timeout")
   _exit(0)

下面是完整的代码示例。

在Linux上,它实现为eventfd(2)

最新更新