I am trying to access the EXIT STATUS of the forked child process from the parent, but I am getting weird answers. Sometimes, I get 256 or sometimes I get a negative number depending upon whether I specify &status or just status. I know I am really close. Can someone provide me with a little help how I will get the EXIT_STATUS
Here is my code
pid_t pid;
int *status;
if((pid = fork()) < 0)
fprintf(stdout, "Error forking child process\n");
else if (pid == 0)
{
execvp(input[0], input);
fprintf(stdout, "Invalid process!!\n");
_exit(EXIT_FAILURE);
}
else
{
while (waitpid(-1, status, 0) != pid);
fprintf(stdout, "The status is %d\n", &status);
}
You’re seeing this behavior because you do not initialize the pointer you’re using, and therefore you are invoking undefined behavior, which means that, quite literally, anything at all might happen. Try changing
statusto be anint(instead of anint*):Your code, on the other hand:
This creates a pointer to int and does not initialize it.
Here you pass this pointer to waitpid(), which will write at the
pointed-to location. Since you have not initialized
the pointer, it’s writing to an unspecified memory
location! This may crash the process or overwrite
allocated memory elsewhere, which may lead to a
spontaneous crash later, or data corruption!
This prints out the address of the pointer variable — not
the value it points to! Using
*statusinstead of&statusmay allow this part to work, but you’restill using an uninitialized pointer.
I would strongly suggest that you turn your compiler’s warning settings up to the maximum (pass
-Wallwith gcc) to make it warn on everything. It would have caught the usage of an uninitialized pointer, and it may have also warned you about using the%dformat specifier with a pointer-type value.