使用C中的exit()和wait()将子进程的值返回到父进程

时间:2015-08-29 08:12:02

标签: linux fork ipc wait exit

status的值未从子进程正确返回到父进程。

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<string.h>
#define BUF_SIZE 200
int main(void){
pid_t pid;
int status=6;
char buf[BUF_SIZE];
pid=fork();
if(pid){
    sprintf(buf,"Value in parent process is %d\n",status);
    write(1,buf,strlen(buf));
    wait(&status);
    sprintf(buf,"Value returned from child process is %d\n",status);
    write(1,buf,strlen(buf));
}
else if(pid==0){
    status++;
    sprintf(buf,"Returning %d..\n",status);
    write(1,buf,strlen(buf));
    exit(status);
}
return 0;
}

代码的输出是:

Value in parent process is 6
Returning 7..
Value returned from child process is 1792

1792来自哪里?为什么这个值不是7

1 个答案:

答案 0 :(得分:2)

因为手册页继续......

   If status 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()!):

   WIFEXITED(status)
          returns true if the child terminated normally, that is, by call‐
          ing exit(3) or _exit(2), or by returning from main().

   WEXITSTATUS(status)
          returns  the  exit  status  of  the child.  This consists of the
          least significant 8 bits of the status argument that  the  child
          specified  in  a  call to exit(3) or _exit(2) or as the argument
          for a return statement in main().  This macro should be employed
          only if WIFEXITED returned true.