求高手指点共享内存的问题
操作系统:64位redhat,想建立共享内存,代码如下:
SHARE_MEM *share_mem_ptr = NULL;
printf("\n create share mem\n");
int shmID = shmget(80045,sizeof(SHARE_MEM),IPC_CREAT+0666);
if(shmID<0)
{
perror("shmget");
}
printf("===== SHMID %d\n", shmID);
share_mem_ptr = (SHARE_MEM *)shmat(shmID, 0, 0);
printf("\n shmat successful ptr %ld",share_mem_ptr);
perror("shmat");
执行结果如下: create share mem
===== QZH SHMID 213975121
shmat: Success
段错误 (core dumped)
请高手指点段错误是怎么回事~~~~
[解决办法]
确认key是合法的,不确认的话先调用ftok获取Key,如果返回-1,则调用creat创建文件,再次调用ftok获取Key,之后shmget。
[解决办法]
SHARE_MEM *share_mem_ptr = NULL; printf("\n create share mem\n");int shmID = shmget(80045,sizeof(SHARE_MEM),IPC_CREAT+0666);if(shmID<0) {perror("shmget");}printf("===== SHMID %d\n", shmID);share_mem_ptr = (SHARE_MEM *)shmat(shmID, 0, 0666|IPC_CREAT); //markprintf("\n shmat successful ptr %ld",share_mem_ptr);perror("shmat");
[解决办法]
给你个我自己的代码吧,运行木有问题的
void *pshared_memory;int m_fd = shmget((key_t)m_key, nSize, IPC_CREAT|IPC_EXCL); if(errno == EEXIST) //打开已存在共享内存 { //printf("EEXIST\n"); m_fd = shmget((key_t)m_key, 0, 0); if(m_fd == -1) { printf("there is some errors for this\n "); assert(0); m_pHead = DY_NULL; } else { pshared_memory = shmat(m_fd, 0, 0666); m_pHead = (SSHheadInfo*)pshared_memory; (m_pHead->nRefCount)++; } return; } pshared_memory = shmat(m_fd, 0, 0666|IPC_CREAT);
[解决办法]
段错误 (core dumped)
是指针出错了,是你上下文中有空指针出现了,或者写错了内存,现存的代码是没有问题的。【我只是加了if (shmctl(shmID, IPC_RMID, 0) < 0)
err_sys("shmctl error");】
main(void){ char* share_mem_ptr = NULL; printf("\n create share mem\n"); int shmID = shmget(80045,64,IPC_CREAT+0666); if(shmID<0) { perror("shmget"); } printf("===== SHMID %d\n", shmID); share_mem_ptr = (char *)shmat(shmID, 0, 0); printf("\n shmat successful ptr %ld",share_mem_ptr); perror("shmat"); if (shmctl(shmID, IPC_RMID, 0) < 0) err_sys("shmctl error"); exit(0);}
[解决办法]
share_mem_ptr = (SHARE_MEM *)shmat(shmID, 0, 0);
改成
share_mem_ptr = (SHARE_MEM *)shmat(shmID, 0, 0666|IPC_CREAT);
[解决办法]