linux 让父进程等待并检查子进程的退出状态

linux 让父进程等待并检查子进程的退出状态

#include
#include
#include
#include
#include
int main(int argv,char* argc[]){
  pid_t pid;
  int n;
  char *message;
  int exit_code;
  printf("fork program staring\n");
  pid=fork();
  switch(pid)
    {
    case -1:
      perror("fork failed");
      exit(1);
    case 0:
      message=("Thsi si the child\n");
      n=5;
      exit_code=37;
      break;
    default:
      message="This is the parent";
      n=3;
      exit_code=0;
      break;
    }
  for(;n>=0;n--){
    puts(message);
    sleep(1);
  }
  if(pid !=0){
    int stat_val;
    pid_t child_pid;
    child_pid=wait(&stat_val);
    printf("Child has finished: PID =%d\n",child_pid);
    if(WIFEXITED(stat_val))
      printf("Child exited with code %d\n",child_pid);
    else
      printf("Child terminated abnormally\n");
  }
  exit(exit_code);
}


你可能感兴趣的:(UNIX/Linux,高级编程实践)