为什么wait()返回-1错误代码? [英] Why wait() returns -1 error code?

查看:523
本文介绍了为什么wait()返回-1错误代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

void fork1()
{
    pid_t id, cpid;
    int status;

    id = fork();

    if (id > 0)
    {
        // parent code
        cpid = wait(&status);
        printf("I received from my child %d this information %d\n", cpid, status);
    }
    else if (id == 0)
    {
        // child code
        sleep(2);
        exit(46);
    }
    else
        exit(EXIT_FAILURE);

    exit(EXIT_SUCCESS);
}

输出为:

我从我的孩子-1收到此信息0

I received from my child -1 this information 0

那么,为什么我在wait之后收到-1错误代码?我希望收到值46作为状态.

So, why I receive the -1 error code after wait? I was expecting to receive the value 46 as status.

如果wait返回-1,我添加了以下代码:

I added the following piece of code if wait returns -1:

printf("errno(%d): %s\n", errno, strerror(errno));

这是输出:

errno(4): Interrupted system call

推荐答案

手册页> 告诉您返回值的含义.

The man page for wait() tells you what the return values mean.

如果由于信号传递到调用进程而导致wait()或waitpid()返回,则应返回-1并将errno设置为[EINTR]....否则,应返回(pid_t)-1和errno设置以指示错误.

If wait() or waitpid() returns due to the delivery of a signal to the calling process, -1 shall be returned and errno set to [EINTR]....Otherwise, (pid_t)-1 shall be returned, and errno set to indicate the error.

要找出errno是什么,可以使用 perror() strerror()

To find out what the errno is, you can use perror() and strerror()

#include <errno.h>
#include <string.h>
// ...
perror("wait error: ");
// or
printf("errno(%d): %s\n", errno, strerror(errno));

wait()手册页中,错误可能是:

From the wait() man page the errors could be:

如果出现以下情况,wait()函数将失败:

The wait() function shall fail if:

ECHILD
调用进程没有现有的等待子进程.
EINTR
该功能被信号中断. stat_loc指向的位置值未定义.

ECHILD
The calling process has no existing unwaited-for child processes.
EINTR
The function was interrupted by a signal. The value of the location pointed to by stat_loc is undefined.

因此,一旦打印出errno值,就应该知道出了什么问题.我没有在您的代码中看到任何具体显示导致它的原因的信息.您可能希望做一些好的做法,并使用-Wall进行编译,并确保您要解决所有警告,并确保初始化所有变量.

So once you print the errno value you should have a good idea what went wrong. I don't see anything in your code specifically showing what caused it. A few things you might want to do as good practice, compile with -Wall and make sure you're addressing all warnings, and also be sure to initialize all variables.

这篇关于为什么wait()返回-1错误代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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