-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 –