未定义引用' shm_open'

时间:2018-01-23 21:16:47

标签: c linux shared-memory

我试图使用共享内存创建一个简单的通信器。

它应该能够写一些文本并将其保存在共享内存中。

有人可以向我解释为什么我会收到错误:

  

未定义引用`shm_open'
  collect2:错误:ld返回1退出状态

我试图为两个程序创建Makefile来编译,但我仍然会遇到错误。

这是我现在正在使用的代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <errno.h>

#define TEXT_SIZE 512

int i;

struct shared_data
{
  int data;
  char some_text[TEXT_SIZE];
};


int main()
{
  struct shared_data *ptr;
  const char *shm_name = "comunicator";
  int shm_fd;
  shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666);

  ftruncate(shm_fd, sizeof(struct shared_data));

  ptr = mmap(0, sizeof(struct shared_data), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
  if (ptr == MAP_FAILED) {
    printf("mmap - failed.\n");
    return -1;
  }

ptr->data = 0;

for(i=0; i<10; i++)
{
        while(ptr->data == 1) sleep(1);
        scanf("%s", ptr->some_text);
        ptr->data = 1;
}



  ptr->data = 0;
  sleep(10);
sprintf(ptr->some_text,"Jakis tekst");
 ptr->data = 1;

 sleep(10);

  if (munmap(ptr, sizeof(struct shared_data)) == -1) {
   printf("unmap failed: %s\n", strerror(errno));
   exit(1);
 }

 if (close(shm_fd)) {
   printf("close failed: %s", strerror(errno));
    exit(1);
  }

  return 0;

}

1 个答案:

答案 0 :(得分:3)

您没有链接在链接阶段定义的库。

http://man7.org/linux/man-pages/man3/shm_open.3.html

-lrt

的关联

ETA 通常,如果你看到&#34;未定义的X&#34;来自编译器的错误,您已经忘记链接到它定义的库中。

相关问题