子进程在调用 fork() 后创建的内存中共享相同的变量 (C)

Child processes are sharing the same variable in memory which is created after fork() is called (C)

我正在编写一个脚本,其中在 for 循环中调用 fork() 以创建许多子项,这些子项执行随机数量的循环,然后打印子项的名称

我有一些奇怪的行为,即 i 所在的内存地址为所有子进程共享,即使变量是在 fork()

之后创建的

这是预期的行为吗?如果是的话,有没有办法将这些变量存储在不同的内存索引中,因为我不希望另一个子进程影响另一个

这是在 childCall 函数中注释掉的打印的一些示例输出

In child 1 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
In child 2 i is located at 0xbef49508
Child 2
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
In child 3 i is located at 0xbef49508
Child 3
In child 1 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 4 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
Child 4
In child 5 i is located at 0xbef49508
Child 1
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
In child 5 i is located at 0xbef49508
Child 5

下面是创建子进程的父函数中的 for 循环,下面是 childCall 函数

谢谢!

for(int i = 0; i<children; i++)
    {
        if(fork() == 0) //If I am the child
        {
            childCall(i + 1);
            return 0;
        }
    }

childCall函数如下

void childCall(int children)
{
    for(int i = 0; i<children; i++)
    {   
        //printf("In child %d i is located at %p\n", children, &i);
        int newrand = rand() % 2; //This implementation is because when I was declaring a random value before the loop all of the children shared the same random value, due to pseudorandomness!
        //printf("%d is the random number\n", newrand);
        i -= newrand;
    }
    printf("Child %d\n", children);
}

fork创建的每个子进程都有自己独立的虚拟内存space。因此,虽然变量在每个进程的虚拟内存中位于相同地址,但它们是独立进程这一事实意味着它们是独立的,并且一个进程中的修改不会影响任何其他进程。