日期:2014-05-16  浏览次数:20633 次

求高手指点共享内存的问题
操作系统: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。
------解决方案--------------------
C/C++ code


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); //mark
printf("\n shmat successful ptr %ld",share_mem_ptr);
perror("shmat");

------解决方案--------------------
给你个我自己的代码吧,运行木有问题的

C/C++ code


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");】

C/C++ code
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);
------解决方案--------------------
探讨

好像是shmget那个函数有问题,难道我指定的id:80045有问题吗?这个id如何指定啊,自己随便设一个不行吗