【问题标题】:When does the wait() function (in LINUX) respond to interrupts?wait() 函数(在 LINUX 中)何时响应中断?
【发布时间】:2014-01-30 20:28:39
【问题描述】:

我有这样的c代码

int childid;
int parentid;
void siginthandler(int param)
{
 // if this is the parent process
 if(getpid() == parentid){
   //handler code which sends SIGINT signal to child process
 kill(childid, SIGINT);
 }
 else // if this is the child process
 exit(0);
}

int main()
{
parentid = getpid(); // store parent id in variable parentid, for the parent as well as child process
int pid = fork();
int breakpid;
if(pid != 0){
childid = pid;
breakpid =  wait();
printf("pid = %d\n", breakpid);
}
else
sleep(1000);
}

现在,当我运行这段代码时,父进程等待,而子进程休眠。如果我现在中断(通过按 ctrl+c)父程序,UNIX(POSIX 标准)文档告诉我等待函数应该返回 -1,errno 设置为EINTR。但是,我的代码实现会杀死子进程,因为父进程将 SIGINT 信号发送给子进程。但是,令人惊讶的是,(在父进程中)wait 不会返回 pid = -1 并将 errno 设置为 EINTR。相反,它返回被杀死的子进程的 id。

对此有解释吗?

【问题讨论】:

    标签: c signals interrupt eintr


    【解决方案1】:

    当您使用signal() 安装信号处理程序时,会发生以下两种情况之一

    1. 大多数系统调用会在信号发生时中断,并将 errno 设置为 EINTR。
    2. 大多数系统调用会在信号发生时自动重新启动(因此它们不会失败并将 errno 设置为 EINTR)。

    这两个取决于你的平台,在你的平台上是2(可能你没有显示任何安装信号处理程序的代码。)

    如果您改为使用sigaction() 安装信号处理程序,您可以使用SA_RESTART 标志控制您想要的12 的行为。

    【讨论】:

    • 谢谢。我现在通过使用 sigaction 获得所需的功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2014-04-21
    • 2020-10-30
    相关资源
    最近更新 更多