Why wait() returns -1 error code?

旧街凉风 提交于 2019-12-11 03:09:49

问题


I have the following code:

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);
}

The output is:

I received from my child -1 this information 0

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

EDIT:

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

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

This is the output:

errno(4): Interrupted system call

回答1:


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

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.

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));

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

The wait() function shall fail if:

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.

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.



来源:https://stackoverflow.com/questions/22405824/why-wait-returns-1-error-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!