我正在尝试学习 C 语言的 child 和 parent 过程

Im trying to learn child and parent process for C language

我写下这段代码来显示每个child和parent的进程id以及变量的变化。 a 和 b 获得了正确的值,但 parent 和 child 没有获得唯一的进程 ID。我试图更改 child 和 parent 的顺序,但它显示了同样的问题。有人可以解释如何正确显示给出不同 PID 的 child 和 parent 吗?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char* argv[]){
int a = 10, b = 25, fq, fr;
fq = fork(); 
if(fq == 0){ 
    a = a + b;
    printf("Process Q(child): The value of a = %d\n, value b = %d\n, and the pid = %i\n", a, b, getpid());
    fr = fork(); 
    if (fr != 0){ 
        b = b + 20;
        printf("Process R(parent): The value of a = %d\n, value b = %d\n, and the pid = %i\n", a, b, getpid()); 
    }
    else{ 
            a = (a * b) + 30;
            printf("Process R(child): The value of a = %d\n, value b = %d\n, and the pid = %i\n", a, b, getpid());
        }
}
else{
    b = a + b - 5;
    printf("Process Q(parent): The value of a = %d\n, value b = %d\n, and the pid = %i\n", a, b, getpid()); 
}
return 0;

}

我收到的输出是:

Process Q(parent): The value of a = 10
, value b = 30
, and the pid = 8141
Process Q(child): The value of a = 35
, value b = 25
, and the pid = 8142
Process R(parent): The value of a = 35
, value b = 45
, and the pid = 8142
Process R(child): The value of a = 905
, value b = 25
, and the pid = 8143

我理论上应该得到的输出是

Process Q(parent): The value of a = 10
, value b = 30
, and the pid = 8141
Process Q(child): The value of a = 35
, value b = 25
, and the pid = 8142
Process R(parent): The value of a = 35
, value b = 45
, and the pid = 8143
Process R(child): The value of a = 905
, value b = 25
, and the pid = 8144

编辑:一直都是正确的。我只是不明白它的概念。检查答案以了解原因。

这是正确的。你有 2 个 fork 但有 4 个 printfs

fq = fork(); 
if(fq == 0){ 
    a = a + b;
    printf(pid of proc 1: 8142);
    fr = fork(); 
    if (fr != 0){ 
        b = b + 20;
        printf(pid of proc 2: 8143); 
    }
    else{ 
            a = (a * b) + 30;
            printf(pid of proc 1: 8142); <<< agan, you are still in the process 1
        }
}
else{
    b = a + b - 5;
    printf(Main process: 8141); 
}

由于并行处理 运行,无法保证消息打印的顺序(除了进程 2 中消息的相对顺序)。我认为8141属于主进程,而8143属于进程1。你可以通过打印的值来验证。但是,字符串输出是行缓冲的,行也可能按轨道顺序出现。