Question

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
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top