简体   繁体   中英

A Query regarding the value of Exit Status of Child Process Created with fork()

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM