多个孩子的pid脱离了同一个父母

PID of multiple children forked off the same parent

本文关键字:同一个 父母 pid 孩子      更新时间:2023-10-16

,所以我拥有此主要功能:

int main() {
cout << "Before fork: " << getpid() << endl;
pid_t pid;
pid = fork();
for (int i = 0; i < 3; ++i) {
    if (pid < 0) {
        cout << "ERROR: Unable to fork.n";
        return 1;
    }
    else if (pid == 0) {
        switch(i) {
            case 0:
                for (int b = 0; b < 10; ++b) {
                    cout << "b " << getpid() << endl;
                    cout.flush();
                }
                break;
            case 1:
                for (int c = 0; c < 10; ++c) {
                    cout << "c " << getpid() <<endl;
                    cout.flush();
                }                    
                break;
            case 2:
                for (int d = 0; d < 10; ++d) {
                    cout << "d " << getpid() << endl;
                    cout.flush();
                }                    
                break;
            default:
                cout << "ERROR" << endl;
                return 1;
        }
    }
    else {
        for (int a = 0; a < 10; ++a) {
            cout << "a " << getpid() << endl;
            cout.flush();
        }
    }
}
return 0;

}

该程序的要点同时运行四个过程,每个过程都会在一定次数上打印一个字符。每当我运行该程序时,我都会发现我生了所有的孩子都有相同的pid。应该这样吗?如果不是/,为什么?

您只创建了一个孩子,然后运行一个循环,在该循环中检查它实际上是孩子。要创建三个孩子,您需要三个拨打fork的电话。即类似的东西:

if ((pid1 = fork()) == 0) {
  // work for first child
  exit(0);
}
if ((pid2 = fork()) == 0) {
  // work for second child
  exit(0);
}
if ((pid3 = fork()) == 0) {
  // work for third child
  exit(0);
}
// work for parent, then:
wait(pid1);
wait(pid2);
wait(pid3);