理解这些过程如何运作的问题

Problem to understand how it works theses processes

晚上好,

我正在使用 fork() 和 waitpid() 系统调用对 C 中的进程进行编程和测试。我了解全局变量的行为,但我不明白为什么当第二个进程完成并返回到第一个进程时,变量 "i" 与第二个进程具有相同的值。

还有为什么当程序回到根进程时,变量"i"的值为2。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int total = 0;
int main(int argc, char **argv) {
    int i, pid;

    for(i = 1; i < 3; ++i) {
        pid = fork();

        if(pid == 0) {
            total = total + i;
            printf("\n");
            printf("Child process %d\n", getpid());
            printf("Parent process %d\n", getppid());
            printf("i = %d\n", i);
        } else {
            waitpid(pid, NULL, 0);
        }
    }
    printf("Child process (end) %d\n", getpid());
    printf("Parent process (end) %d\n", getppid());
    printf("total = %d\n", total);
    printf("i = %d\n", i);
    exit(0);
}

这是执行的结果

Child process 9191
Parent process 9190
i = 1

Child process 9192
Parent process 9191
i = 2

Child process (end) 9192
Parent process (end) 9191
total = 3
i = 3

Child process (end) 9191
Parent process (end) 9190
total = 1
i = 3

Child process 9193
Parent process 9190
i = 2

Child process (end) 9193
Parent process (end) 9190
total = 2
i = 3

Child process (end) 9190
Parent process (end) 2876
total = 0
i = 3

我有一个建议:就是函数waitpid()把资源拿给子进程,但是不能解释根进程中变量"i"的值

我希望我已经清楚我的问题并为我的一点点糟糕的英语感到抱歉。

感谢您的回答。

以下更正代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 清楚地表明父进程中的 total 未被子进程更改

现在,建议的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int total = 0;


int main( void )   // <<-- corrected statement
{
    int i, pid;

    for(i = 1; i < 3; ++i) 
    {
        pid = fork();

        if(pid == 0) 
        {
            total = total + i;
            printf( "\n") ;
            printf( "Child process %d\n", getpid() );
            printf( "Parent process %d\n", getppid() );
            printf( "i = %d\n", i );
            exit( 0 );    // <<-- added statement
        } 

        else 
        {
            waitpid( pid, NULL, 0 );
        }
    }

    printf( "Child process (end) %d\n", getpid() );
    printf( "Parent process (end) %d\n", getppid() );
    printf( "total = %d\n", total );
    printf( "i = %d\n", i );
    exit( 0 );
}

以上代码的输出为:

Child process 10378
Parent process 10377
i = 1

Child process 10379
Parent process 10377
i = 2
Child process (end) 10377
Parent process (end) 10375
total = 0
i = 3

然而,代码无法检查函数的错误情况:fork() 因此,如果对 fork() 的调用失败,将导致重大失败。 IE。代码应该(也)检查调用 fork() 和调用

的返回值 -1
if( pid < 0 )
{
    perror( "fork failed");  
    exit( 1 );`
}