apue p194页 一个有意思 的demo

来源:互联网 发布:淘宝网鞋子女鞋春季 编辑:程序博客网 时间:2024/06/05 18:04
  习惯直接上代码 ,实现功能是fork一个子进程,不想它等待子进程直接退出,也就是fork2次,之前看见一个哥们说为什么父进程退出,子进程和孙子进程为何getppid都是1,其实是错误的自己没有认真研究代码,其实父进程和子进程都退出了,就留下了孙子进程执行;
#include<stdio.h>  2 #include<unistd.h>  3 #include<string.h>  4 #include<sys/wait.h>  5 #include<errno.h>  6 int main(void)  7 {  8         pid_t pid;  9         if((pid=fork()) < 0){       //创建进程 10                 fprintf(stderr , "fork error : %s \n" , strerror(errno)); 11                 exit(1); 12         }else if(pid == 0){ 13                 printf("this's process id: %d\n" , getpid()); 14                 sleep(2);  15                 if((pid = fork()) < 0){           //再次创建进程 16                         fprintf(stderr , "fork error :%s\n", strerror(errno)); 17                         exit(2); 18                 } 19                 else if(pid > 0) 20                         exit(0);        //第1个子线程在这里退出的 21                 sleep(2); 22                 printf("second child  , parent pid = %ld\n" , (long)getppid()); 23                 exit(0); 24         } 25          26         if(waitpid(pid , NULL ,0) != pid){ 27                 fprintf(stderr , " waipid error:%s\n" , strerror(errno)); 28                 exit(3); 29         } 30         printf("this's process id: %d\n" , getpid()); 31         exit(0); 32  33 }输出: this's process id: 3649[root@xc p193]# second child  , parent pid = 1其实之前也没太搞明白,所以就加了两个print。孙子进程获取父进程id为一的原因在于被init进程继承过去了


0 0