ubuntu 父进程终止,子进程没有被init(1)进程领养问题

fork一个子进程,在子进程中打印父进程终止前后的PPID: 一般会打印父进程的PID,然后会打印init(PID=1)。因为子进程转为孤儿进程被init进程收养。如果不希望子进程终止,也不希望处于僵死状态直到父进程终止,可以使用两次fork,如:

  4 int main(void)
  5 {
  6     pid_t pid;
  7     if((pid = fork()) < 0)
  8         err_sys("fork error");
  9     else if(pid == 0) /*first child*/
 10     {
 11 
 12         if((pid = fork()) < 0)
 13             err_sys("fork error");
 14         else if(pid > 0)
 15         {
 16             printf("parent %ld\n",(long)getppid());
 17             exit(0);/*parent from second fork == first child*/
 18         }
 19     
 20         sleep(2);
 21         printf("second child,parent pid = %ld\n",(long)getppid());
 22         exit(0);
 23 
 24     }
 25     if(waitpid(pid,NULL,0) != pid) /*wait for first child*/
 26         err_sys("waitpid error");
 27       printf("%ld\n",(long)getpid());
 28         printf("%d\n",pid);
 29     exit(0);
 30 
 31     
 32 }                                                                  

编译再ubuntu上运行的情况如下:

parent 7064
7064
7065
my-linux@vlinux:~/qt_work/linux/pthread$ second child,parent pid = 1948

发现运行后,第二个子进程其父进程结束之后,感觉好像没被init(1)进程收养,而是被PID 1948进程收养

查看ubuntu init进程

my-linux@vlinux:~/qt_work/linux/pthread$ ps aux | grep init
root         1  0.0  0.2 119872  4968 ?        Ss   09:00   0:01 /sbin/init splash
my-linux  7080  0.0  0.0  15960  1028 pts/18   S+   17:59   0:00 grep --color=auto init

查看ubuntu下PID为1948的进程为/sbin/upstart --user

my-linux@vlinux:~/qt_work/linux/pthread$ ps aux | grep 1948
my-linux  1948  0.0  0.2  48216  4276 ?        Ss   09:02   0:00 /sbin/upstart --user
my-linux  7076  0.0  0.0  15960  1016 pts/18   S+   17:58   0:00 grep --color=auto 1948

这是为什么呢?

原来ubuntu使用Upstart作为默认init系统,以下是网上的资料:


Upstart can now run as a normal user process (whose PID is not 1) both as root or as a non-privileged user by passing the --user option. This feature is employed to supervise a user's desktop session (technically those sessions listed in /etc/upstart-xsessions). The Session Init is started /etc/X11/Xsession.d/99upstart which starts a Session Init for a user.

Upstart is now used to supervise a user's desktop session. To see details of the running Upstart session, either echo $UPSTART_SESSION (用这个命令可以查看本机--user的属性)to see the D-Bus address the Session Init process is listening to.

--user (Running a Session Init)
Runs Upstart as a Session Init.


 

你可能感兴趣的:(Linux编程)