0

Just have a query about Status of Child processes created with fork()

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(4);
        exit(1);
       }

  waitpid(pid, &status, 0);

  printf("The status of child is %u\n",status);


  printf("Parent: %d\n", getpid());

  return 0;
  }

I expect the status to print 1 , but it prints 256(a byte of 0's is added )

Can someone explain why is this? I am a newbie to C , so please excuse as this question may appear silly to the experts.

  • Either use `WEXITSTATUS(status)` or do `status >> 8`. – Achal May 28 '19 at 06:40
  • Possible duplicate of [Why does wait() set status to 256 instead of the -1 exit status of the forked process?](https://stackoverflow.com/questions/3659616/why-does-wait-set-status-to-256-instead-of-the-1-exit-status-of-the-forked-pr) – Achal May 28 '19 at 06:41
  • Another duplicate [I used wait(&status) and the value of status is 256, why?](https://stackoverflow.com/questions/24130990/i-used-waitstatus-and-the-value-of-status-is-256-why) – Achal May 28 '19 at 06:42

1 Answers1

2

From man waitpid:

If wstatus is not NULL, wait() and waitpid() store status information in the int to which it points. This integer can be inspected with the following macros (which take the integer itself as an argument, not a pointer to it, as is done in wait() and waitpid()!):

WEXITSTATUS(stat_val)

If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().

So you should:

printf("The status of child is %u\n", WEXITSTATUS(status));
KamilCuk
  • 120,984
  • 8
  • 59
  • 111