解释这段代码的工作原理; 子进程如何返回值以及在哪里?

May*_*xit 2 c fork child-process data-structures

我不知道子进程返回的值是怎么回事?

输出为6,7; 问题来源:http://www.cs.utexas.edu/~mwalfish/classes/s11-cs372h/hw/sol1.html

Program 1: 
main() 
{ 
    val = 5; 
    if(fork()) 
    wait(&val); 
    val++; 
    printf("%d\n", val); 
    return val; 
}
Run Code Online (Sandbox Code Playgroud)

Vau*_*ato 5

主要流程:

val = 5; 
wait(&val); // wait until child finishes
Run Code Online (Sandbox Code Playgroud)

子进程:

val++; // val becomes 6
printf("%d\n", val); // prints 6
return val; // return val back to main process
Run Code Online (Sandbox Code Playgroud)

主要流程:

wait(&val); // val becomes 6
val++; // val becomes 7
printf("%d\n", val); // prints 7
return val; 
Run Code Online (Sandbox Code Playgroud)