当前位置: 技术问答>linux和unix
Unix 共享内存core问题
来源: 互联网 发布时间:2017-03-21
本文导语: 这两天再学习共享内存的东西,写了个小例子,但是发现连接共享内存返回的地址赋值给char *writemsg,然后断开共享内存连接,使 writemsg=NULL;再进行writemsg的赋值时,程序会core掉 不明白是啥情况,不是置为NULL就可以...
这两天再学习共享内存的东西,写了个小例子,但是发现连接共享内存返回的地址赋值给char *writemsg,然后断开共享内存连接,使 writemsg=NULL;再进行writemsg的赋值时,程序会core掉
不明白是啥情况,不是置为NULL就可以使用了么??再第二个重连后再赋值就不会core
具体看下面代码注释的地方
int main()
{
int shm_id;
key_t key = 0xb0000001;
char *writemsg ;
char *readmsg ;
printf("key is:%xn",key);
if((shm_id = shmget(key,32,0666|IPC_CREAT))==-1)
{
printf("connet 0xb0000001 errorn");
}else{
printf("connet 0xb0000001 successn");
printf("shm_id is:%dn",shm_id);
}
writemsg = (char *) shmat(shm_id,0,0);
strcpy(writemsg,"this is what I want to write to the shm");
shmdt((void *)writemsg);
writemsg = NULL;
//这里memcpy()会core掉
memcpy(writemsg,"want to write to the shm",sizeof(writemsg));
if((readmsg = (char *) shmat(shm_id,0,0))
不明白是啥情况,不是置为NULL就可以使用了么??再第二个重连后再赋值就不会core
具体看下面代码注释的地方
int main()
{
int shm_id;
key_t key = 0xb0000001;
char *writemsg ;
char *readmsg ;
printf("key is:%xn",key);
if((shm_id = shmget(key,32,0666|IPC_CREAT))==-1)
{
printf("connet 0xb0000001 errorn");
}else{
printf("connet 0xb0000001 successn");
printf("shm_id is:%dn",shm_id);
}
writemsg = (char *) shmat(shm_id,0,0);
strcpy(writemsg,"this is what I want to write to the shm");
shmdt((void *)writemsg);
writemsg = NULL;
//这里memcpy()会core掉
memcpy(writemsg,"want to write to the shm",sizeof(writemsg));
if((readmsg = (char *) shmat(shm_id,0,0))