关于fork的一个疑问

C语言 码拜 8年前 (2016-06-05) 1006次浏览
先贴代码,如下:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
        pid_t pid = fork();
        if(pid == 0){
                printf("This message from new.\t");
                printf("My PID is: %d\t", getpid());
                printf("My ppid is: %d\n", getppid());
        }else{
                printf("This message from old.\t");
                printf("This new proccess" PID is: %d\t", pid);
                printf("My PID is: %d\n", getpid());
        }
}

编译以后运行结果:

[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2155 My PID is: 2154
This message from new.  My PID is: 2155 My ppid is: 1
[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2157 My PID is: 2156
This message from new.  My PID is: 2157 My ppid is: 1
[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2159 My PID is: 2158
This message from new.  My PID is: 2159 My ppid is: 1
[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2161 My PID is: 2160
This message from new.  My PID is: 2161 My ppid is: 2160
[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2163 My PID is: 2162
This message from new.  My PID is: 2163 My ppid is: 2162
[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2165 My PID is: 2164
This message from new.  My PID is: 2165 My ppid is: 1
[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2167 My PID is: 2166
This message from new.  My PID is: 2167 My ppid is: 2166
[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2169 My PID is: 2168
This message from new.  My PID is: 2169 My ppid is: 1
[root@localhost proccess]# ./a.out 
This message from old.  This new proccess" PID is: 2171 My PID is: 2170
This message from new.  My PID is: 2171 My ppid is: 1

我们可以通过结果看到。很多时候克隆出来的进程在调用getppid获取父进程ID的时候,得到的是1,而不是调用fork的进程的ID。有时候又是调用fork的进程的ID。这是怎么一回事儿呢?

解决方案

20

http://stackoverflow.com/questions/16078188/why-getppid-from-the-child-return-1
在子进程调用 getppid 时,父进程已经退出了

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于fork的一个疑问
喜欢 (0)
[1034331897@qq.com]
分享 (0)