Why do processes I fork get systemd as their parent?

前端 未结 3 1420
死守一世寂寞
死守一世寂寞 2021-01-13 05:15

I am learning fork() in Linux, and here is my program:

  1 #include 
  2 #include 
  3 #include 
  4 int main(         


        
3条回答
  •  日久生厌
    2021-01-13 05:45

    It is because the parent process terminates first. In Linux there are no ophan processes. They are assigned to the init process.

    If you want to control your processes so that child process terminates first, make parent process wait. Using wait() sys_call.

    Example:
    
       #include 
       #include 
       #include 
       int main(void)
       {
            int pid;
            int pid2;
            pid = fork();
            if(pid < 0){
                     exit(1);
            }
            if(pid == 0){ // child process
                pid2 = fork()
                if (pid2 < 0)
                    exit(1);
                if (pid2 == 0)
                {
                    printf("pid:%dppid:%d\n",getpid(),getppid());
                    exit(0);
                }
                wait();
                printf("pid:%d ppid:%d\n",getpid(),getppid());
                exit(0);
            }
            else{         // parent process
               wait();
               printf("parent pid:%d ppid:%d\n",getpid(),getppid());
               exit(0);
            }       
            return 0;            
      }
    

    systemd is an init system used in Linux distributions to bootstrap the user space and manage all processes subsequently

提交回复
热议问题