c - 写入共享内存时出现段错误

标签 c

请帮忙检查以下代码:在linux上运行遇到段错误。

#deinf QID 2012

typedef struct {
   pid_t       pid;
   pthread_t   tid;
   char        msg;
} MSG;

typedef struct {
   int    q_head;
   int    q_rear;
   MSG    msgbuf[16*1024];
} QUE;

int attach_que(int que_name, int *shmid, void *shm_ptr)
{

   *shmid = shmget((key_t)que_name, sizeof(QUE), 0666 | IPC_CREAT);
   if (*shmid == -1)
   {
      printf("%d:%d failed to get shared memory.\n", getpid(),que_name);
      return -1;
   }

   printf("%d:is attaching to share memory %d.\n", getpid(), *shmid);

   shm_ptr = shmat(*shmid, (void *)0, 0);
   if (shm_ptr == (void *)-1)
   {
      printf("%d:%d failed to attch to shmget.\n", getpid(),que_name);
      return -1;
   }

   printf("%d: attched to share memory %d.\n", getpid(),*shmid);
   return -1;

}

int main()
{

   void        *shm_ptr = NULL;
   TDM_QUE     *tdm_que_ptr;
   DMINT       shmid;
   pid_t       pid;

   pid = getpid();

   printf("L-SIMCO %d:is starting.\n", pid);

   attach_tdm_que(Q_LSIMCO, &shmid, shm_ptr);
   printf("LSMICO %d:shared memory 0x%x as Q_%d.\n", pid, shm_ptr, Q_LSIMCO);
   tdm_que_ptr = (TDM_QUE *)shm_ptr;
   tdm_que_ptr->q_head = 0;
   tdm_que_ptr->q_rear = 0;

   /* if this is not first time when creating shared memory, do not init data */
   if (tdm_que_ptr->is_creat != 777777)
   {
      printf("%d: Init shared memory 0x%x by LSIMCO %d.\n", pid, shm_ptr, Q_LSIMCO);
      /* init data for shared memory */

      tdm_que_ptr->is_creat = 777777;
   }

   printf("%d is reading shared memory 0x%x.\n",pid,shm_ptr);
   ...
}
=========================
Running result is following:
-bash-3.2$ ./lsimco
 6341:is starting.
 QUE is size of 4620
6341:is attaching to share memory 0.
6341: attched to share memory 0.
6341:shared memory 0x0 as Q_2012.
Segmentation fault

谢谢。

最佳答案

您必须在 attach_que 调用中使用 **shm_ptr 才能返回有效的指针。所以,你的电话必须是我:

attach_tdm_que(Q_LSIMCO, &shmid, &shm_ptr);

当然,在attach_tdm_que内部,正确使用指针指定:

*shm_ptr = shmat(*shmid, (void *)0, 0);
if (*shm_ptr == (void *)-1)
{
    printf("%d:%d failed to attch to shmget.\n", getpid(),que_name);
    return -1;
}

更多内容:您总是从 attach_tdm_que 返回 -1。 此外,始终发布可编译的代码。

关于c - 写入共享内存时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9326360/

相关文章:

c - 为什么只有代码块给我返回错误(0xc00000FD)?

c - haskell FFI传入和传出C结构数组

c - 使用什么来代替 sizeof(void)?

c - linux和windows关于颜色的问题

c - 如何在 C 中将字符串添加到 PUNICODE_STRING 的末尾

c - qsort() : Sorting only even numbers of an array

c - Unix 域套接字 : Using datagram communication between one server process and several client processes

c - 错误免费(): Invalid next size (fast)

c - 需要重新提示用户以防他输入数字而不是字母

c - 具有递归和给定结构的 BST