问题描述
在此C程序中,数据没有被处理,即父子进程间共享。孩子有它自己的数据和家长都有它自己的数据,但指针显示相同的地址,这两个过程。它是如何被背景做了什么?是否叉产生相同数据的副本?如果这样的话,我们有相同的指针的地址,这两个过程。或者是由于正在复制每个进程的静态分配的数据,并为每个处理中的数据是独立?我想知道它是怎么正在做?
In this C program, data is not being shared between process i.e. parent and child process. child has it's own data and parent has it's own data but pointer is showing the same address for both processes. How it is being done on background? Does fork generates copies of same data? if so then we have the same pointer's address for both processes. Or is it due to the statically allocated data that is being copied for each process and the data is independent for each process? I want to know how it is being done?
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
//Static Array
int X[] = {1,2,3,4,5};
int i, status;
//The fork call
int pid = fork();
if(pid == 0) //Child process
{
//Child process modifies Array
for(i=0; i<5; i++)
X[i] = 5-i;
//Child prints Array
printf("Child Array:\t");
for(i=0; i<5; i++)
printf("%d\t", X[i]);
printf("\nArray ptr = %p\n", X);
}
else //Parent process
{
// Wait for the child to terminate and let
// it modify and print the array
waitpid(-1, &status, 0);
//Parent prints Array
printf("Parent Array:\t");
for(i=0; i<5; i++)
printf("%d\t", X[i]);
printf("\nArray ptr = %p\n", X);
}
return 0;
}
下面是程序的输出。
1 Child Array: 5 4 3 2 1
2 Array ptr = 0x7fff06c9f670
3 Parent Array: 1 2 3 4 5
4 Array ptr = 0x7fff06c9f670
在子过程中修改阵列应该也修改父进程的数据。这是怎么回事在后台?
When child process modifies array it should have also modified the data of parent process. What is going on in background?
推荐答案
在叉
的新工艺,新的子进程是一个的复制的父进程的。这就是为什么指针等等都是平等的。由于的的奇观虚拟内存的两个过程可以有相同的内存映射,但仍使用不同的内存。
When you fork
a new process the new child process is a copy of the parent process. That's why pointers etc. are equal. Due to the wonders of virtual memory two processes can have the same memory map, but still be using different memory.
这篇关于在进程间共享数据时,我们在C使用叉子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!