linux共享内存异常,Linux共享内存分段故障

我正在学习有关的共享内存,并创造了这个示例程序来测试的事情了Linux共享内存分段故障

//IPC - Shared Memory

#include

#include

#include

#include

#include

int main(int argc, char* argv[])

{

printf("setting up shared memory\n");

key_t ipc_key;

int shmid;

int pid;

ipc_key = ftok(".",'b');

if((shmid=shmget(ipc_key, 32, IPC_CREAT|0666))==-1)

{

printf("error creating shared memory\n");

exit(1);

}

printf("shared memory created with id %d\n",shmid);

//fork a child process

pid = fork();

printf("fork result %d\n",pid);

if(pid==0)

{

//child process

//attach the shared memory

int* shm_add_child = (int*)shmat(shmid, 0,0);

printf("child attached to shared mem at address %p\n",(void*)shm_add_child);

while(1)

{

printf("%d\n",*shm_add_child);

printf("a\n");

}

//detach from shm

shmdt(shm_add_child);

}

else

{

//parent process

int* shm_add_parent;

shm_add_parent = (int*)shmat(shmid, 0,0);

printf("parent attached to shared mem at address %p\n",(void*)shm_add_parent);

*shm_add_parent = 10;

sleep(10);

//detach from shm

shmdt(shm_add_parent);

}

//remove shm

shmctl(shmid, IPC_RMID,0);

exit(0);

}

然而,当我运行它,我得到段错误。看来我对共享内存的指向是不对的。也没有什么是从子过程中的无限循环中打印出来的。

[email protected]:~/Desktop/week1_tasks$ ./ipc_sharedmem_a

setting up shared memory

shared memory created with id 5996570

fork result 8703

parent attached to shared mem at address 0xffffffff991aa000

fork result 0

child attached to shared mem at address 0xffffffff991aa000

Segmentation fault (core dumped)

这里怎么回事?

2016-07-15

Ankit

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值