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
The man page for
wait()
tells you what the return values mean.To find out what the
errno
is, you can useperror()
andstrerror()
From the
wait()
man page the errors could be:The
wait()
function shall fail if: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.