【发布时间】:2012-07-21 09:50:59
【问题描述】:
给定以下代码:
#include <sys/types.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/types.h>
int main()
{
int arr[100];
int shmid = shmget(IPC_PRIVATE, sizeof(int), 0600);
int *ptr = shmat(shmid, NULL, 0);
*ptr = 42;
arr[0] = 1;
if (fork())
{
wait(NULL);
printf("%d, %d\n",arr[0],*ptr);
}
else
{
arr[0] = 2;
*ptr = 1337;
}
return 0;
}
输出为:1,1337。
问题:为什么不是2,1337?
如果孩子更新 arr 和 ptr 是他的块怎么可能?意思是,父进程在fork()发生之前将arr[0]更新为1,那么为什么ptr发生了更新而arr[0]的值没有更新为2呢?
最好的问候
【问题讨论】:
-
确保最终释放共享内存对象,因为这些对象将在您的程序终止后继续存在。另见stackoverflow.com/a/10685112/1025391
标签: c linux fork shared-memory