试图理解fork函数返回值的逻辑

时间:2017-07-10 08:28:31

标签: c++ linux operating-system

考虑这个简单的程序:

using namespace std;

int main(int argc, const char * argv[]) {
    cout << "first pid: " << getpid() << endl;
    int a = fork();
    int b = fork();
    cout << a << " " << b << endl;
    return 0;
}

所以我一遍又一遍地运行它,并试图了解每次运行中发生的模式是什么。我根本不明白数字方面发生了什么。我最初在叉子之前打印了pid,然后我再也看不到那个pid,好像它被改变了什么的。我添加了2个不同的输出作为参考:

first pid: 64538
64541 64542
64541 0
0 64543
0 0

first pid: 64625
64628 64629
0 64630
0 0
64628 0

我所理解的是,现在有4个进程处于活动状态,因为第一个fork产生了2个进程,第二个fork将它们分为4个进程。 我不明白的是打印到控制台的ID的逻辑。

3 个答案:

答案 0 :(得分:2)

这是一张正在发生的事情的表格:

gen_0     | gen_1         | gen_2_0       | gen_2_1
          |               |               |
==[ before first fork ]==================================
started   |               |               |
pid = 123 |               |               |
          |               |               |
--[ after first fork ]===================================
          | started       |               |
          | pid = 1111    |               |
          | parent: gen_0 |               |
a = 1111  | a = 0         |               |
          |               |               |
--[ after second fork ]==================================
          |               | started       | started
          |               | pid = 2222    | pid = 3333
          |               | parent: gen_0 | parent: gen_1
a = 1111  | a = 0         | a = 1111      | a = 0
b = 2222  | b = 3333      | b = 0         | b = 0

答案 1 :(得分:0)

&#39>逻辑&#39;是零意味着你是fork()的孩子,-1表示错误,任何正数是孩子的PID,你是父母。< / p>

没有指定的&#39;逻辑&#39;至于如何分配PID。不要找任何人。

答案 2 :(得分:0)

我在OP中添加了评论来描述会发生什么:

using namespace std;

int main(int argc, const char * argv[]) {
    cout << "first pid: " << getpid() << endl;
    int a = fork();
    // from here two processes run:
    // in parent a is PID of child
    // in child a is 0
    int b = fork();
    // from here four processes run:
    // a is for parent and child identical 0 or PID
    // in parents b is PID of child
    // in children b is 0
    // Thus, the following shows all 4 combinations of 0 and not 0.
    cout << a << " " << b << endl;
    return 0;
}