2015-08-29 1 views
2

Значение status не возвращается корректно от дочернего элемента к родительскому процессу.Возвращаемое значение из дочернего процесса в родительский процесс с помощью exit() и wait() в C

#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?

ответ

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. 

 Смежные вопросы

  • Нет связанных вопросов^_^