简体   繁体   English

使用 fork() 在子进程中没有获得适当的父 ID

[英]Not getting appropriate parent id in child process using fork()

I am trying to get the parent id in the child process using fork() .我正在尝试使用fork()获取子进程中的父 ID。 However, I don't get the proper parent id.但是,我没有得到正确的父 ID。 Sometime I do and sometime I don't.有时我会,有时我不会。 My printf prints 1 for the parent id.我的printf为父 ID 打印 1。 Here is my code snippet.这是我的代码片段。 Can anyone explain the reason.任何人都可以解释原因。

for(i = 1 ; i <= n ; i++){      
    if((pid = fork()) == 0){
        printf("Parent id is %u\n", getppid()) ;            
        break ;
    }
}  

The process with the id of 1 is the init process. id为1的进程是init进程。 Output from top -p 1 (on my Ubuntu machine): top -p 1输出(在我的 Ubuntu 机器上):

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND             
    1 root      20   0 24732 2704 1376 S    0  0.0   0:00.93 init

If a process is orphaned the init process adopts the orphaned process , and getppid() will return 1 in the orphaned process.如果进程被孤立, init进程采用孤立进程,并且getppid()将在孤立进程中返回1 In your case, the parent process must be exiting, on occasion, before the child process calls getppid() .在您的情况下,有时在子进程调用getppid()之前,父进程必须退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM