Linux下C,waitpid函数()由处理信号,返回值-1,并将errno 5

问题描述:

我就遇到了这个问题,几个小时前畅通。Linux下C,waitpid函数()由处理信号,返回值-1,并将errno 5

即使我有固定的,我只是不明白为什么会这样。

signal(SIGHUP, sighupHandler); 
. 
. 
. 
// sync with child by getting a char written by child 
fgetc(pipe_in); 
close(pipe_in); 
int status; 
if(waitpid(initProcessPid, &status, 0) == -1){ 
    printf("debug: errno is %d\n", errno); 
    printf("failed to wait for init process to end\n"); 
} 

每次waitpid函数()块中一个SIGHUP发生,waitpid函数()返回-1,并将errno 5.

虽然EINTR应该在错误号由ALK指出这种情况下,是EINTR 4,不是5

几个小时收集来自gdb的想法,因为我没有真正在做什么SIGHUP当前之后,我改变了我的代码:

signal(SIGHUP, SIG_IGN); 

然后它工作正常,SI GHUP不再打破waitpid()模块。

我是工作在Linux容器,其目的是单个文件和静态的。 https://github.com/Kethen/minicontainer

+1

https://stackoverflow.com/q/41474299/2371524 –

+0

来自['waitpid()'的POSIX文档](http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html) (Linux的手册页基本上是一样的):“*** ERRORS ** 如果发生以下情况,waitpid()函数将失败:[...] [EINTR] 函数被信号中断。 ..]“*” – alk

+2

另外,不要使用'signal()',因为它的语义不同;请务必使用['sigaction()'](http://man7.org/linux/man-pages/man2/sigaction.2.html)。另外,如果同时包含''和'',则可以使用'strerror(errno)'获取可读的错误字符串。 –

作为每wait()/waitpid() POSIX documentaion

wait()功能须安排调用线程阻塞变得直到由子进程终止产生的状态信息提供给线程,或直至分娩的信号,其作用是任一执行信号捕获函数或终止进程,或发生错误。

如果由于信号到调用进程的递送wait()waitpid()回报,-1应退还和errno设置为[EINTR]

由于您已经配置了SIGHUP来执行一个函数,所以它被上面的强调子句覆盖。

这与许多其他系统调用时信号中断,可以返回EAGAIN。你可以处理它的方法之一是用类似代码:

// Keep waiting while being interrupted. 

int rc, err; 
do { 
    rc = waitpid (initProcessPid, &status, 0); 
    err = errno; 
} while ((rc == -1) && (err == EINTR)); 

// Any error other than interruption will be caught here. 

if (rc == -1) { 
    printf ("debug: errno is %d\n", err); 
    printf ("failed to wait for init process to end\n"); 
} 

你也是正确的认为Linux一般规定,这应该是4而不是5但事实并非总是如此。有些系统使用大不相同的值(如IBM iSeries,将这些常见错误代码放在3400左右的某处)。

你应该检查对特定而不是一个固定值。