Linux fork () 函数的一个小问题

zhangyuxiu · 2013年11月25日 · 最后由 kevinxu 回复于 2014年02月10日 · 2615 次阅读

自己测试写了一个程序:

#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main(){
    cout << "son/parent\tppid\tpid\tspid"<<endl;
    pid_t spid = fork();
    if (spid<0) cout << "error" <<endl;
    else if (spid!=0) cout << "\t" << "parent" << "\t" << getppid() << "\t" << getpid() << "\t" << spid << endl;
    else {
        cout << "\t" << "son" << "\t" << getppid() << "\t" << getpid() << "\t" << spid << endl;
    }
    return 0;
}

执行结果如下:

son/parent  ppid    pid spid
parent  32278   32343   32344
son 1   32344   0

问题:fork() 后,产生的子进程的父进程的 pid 为什么是 1?我感觉应该是 32343 啊。。。求解释。

@zhangyuxiu 父进程如果先于子进程退出,子进程会被 init 进程接管,init 的进程号为 1, 看此例很有可能是这个原因造成的。你可以在父进程代码里 sleep 10 再看看正常否?

ps: 请排下版。

#1 楼 @lyfi2003 哦,受教了!谢谢你!

父进程先于子进程技术了,一般会通过 wait(child_pid) 做到等待。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号