是否存在设置超时的 wait() 系统调用版本? [英] Is there a version of the wait() system call that sets a timeout?

查看:18
本文介绍了是否存在设置超时的 wait() 系统调用版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使用忙等待或忙睡眠循环之外,还有什么方法可以使用 wait() 系统调用超时?

Is there any way to use the wait() system call with a timeout, besides using a busy-waiting or busy-sleeping loop?

我有一个父进程,它 forks 本身和 execs 子可执行文件.然后它等待子进程完成,以任何适当的方式获取其输出,并执行进一步的处理.如果该进程在一定时间内没有完成,则假定其执行超时,并执行其他操作.不幸的是,鉴于问题的性质,这种超时检测是必要的.

I've got a parent process that forks itself and execs a child executable. It then waits for the child to finish, grabs its output by whatever means appropriate, and and performs further processing. If the process does not finish within a certain period of time, it assumes that its execution timed out, and does something else. Unfortunately, this timeout detection is necessary given the nature of the problem.

推荐答案

没有等待超时的调用.

您可以做的是安装一个为 SIGCHLD 设置标志的信号处理程序,并使用 select() 来实现超时.select() 将被信号中断.

What you can do instead is install a signal handler that sets a flag for SIGCHLD, and use select() to implement a timeout. select() will be interrupted by a signal.

static volatile int punt;
static void sig_handler(int sig)
{
    punt = 1;
}

...

struct timeval timeout = {10,0};
int rc;

signal(SIGCHLD, sig_handler);

fork/exec stuff
//select will get interrupted by a signal

rc = select(0, NULL,NULL,NULL, &timeout ); 
if (rc == 0) {
// timed out
} else if (punt) {
    //child terminated
}

如果您还需要处理其他信号,则需要更多逻辑

More logic is needed if you have other signal you need to handle as well though

这篇关于是否存在设置超时的 wait() 系统调用版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆