【问题标题】:Returning value from child process to parent process using exit() and wait() in C使用C中的exit()和wait()将值从子进程返回到父进程
【发布时间】:2015-11-23 21:07:29
【问题描述】:

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

【问题讨论】:

    标签: linux fork ipc wait exit


    【解决方案1】:

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

       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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2018-04-05
      • 2020-06-18
      • 2018-09-09
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多