多个孩子的PID分叉了同一个父母

时间:2014-01-31 05:11:33

标签: c++ fork

所以我有这个主要功能:

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。它应该是那样的吗?如果不是/为什么?

1 个答案:

答案 0 :(得分:1)

您只创建了一个子项,然后运行一个循环,在该循环中,它检查实际上是子项的三次。要创建三个孩子,您需要三次调用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);