-1
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
void forkexample()
{
int x = 1;
if (fork() == 0)
{
//printf("this is Child ");
++x;
printf("addr of x=%p\n",&x);
int* arr1=(int*)malloc(sizeof(int)*5);
*arr1=5;
printf("Addr of child arr1=%p arr1[0]=%d\n",&arr1,arr1[0]);
}
else
{
//printf("this is parent ");
--x;
printf("addr of x=%p\n",&x);
int* arr2=(int*)malloc(sizeof(int)*5);
*arr2=6;
printf("Addr of parent arr2=%p arr2[0]=%d\n",&arr2,arr2[0]);
}
}
int main()
{
forkexample();
return 0;
}
为什么& ARR1 = & ARR2?
我知道操作系统将使用写时复制(COW)方法为子进程创建新的地址空间,'&'给出逻辑地址,但这里我们在这里动态创建2个不同的数组。
感谢关于%p,但在父进程和子进程中,无论使用malloc()分配多大的大小,sizeof运算符都会给出恒定大小= 0x4(即int的大小)。 –
@ShashankRao然后我想这就是你平台上指针的大小。 – melpomene
int * arr1 = malloc(sizeof(int)* 5),但在正常情况下,它应该给5 * sizeof int即5 * 4 = 20B –