Ubuntu C代码对“ shm_open”的未定义引用

时间:2019-05-19 22:26:51

标签: c ubuntu

尝试打开共享内存时出现此错误。我的操作系统是Linux Ubuntu。我喜欢分配和取消分配内存,我喜欢创建一个读写器,并且我喜欢这两个进程将共享内存。这是经典的IPC。

/usr/bin/ld: /tmp/ccYDB3mT.o: in function `main':
SharedMemory.c:(.text+0x1a): undefined reference to `shm_open'
collect2: error: ld returned 1 exit status

此代码最初试图从整数获取内存。

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

int main(void){
    // Open Shared memory 
    //Get the handle to the shared memory area 
    int fd;
    unsigned char *addrPtr;

    fd = shm_open("/program.shared", O_RDWR | O_CREAT , S_IREAD | S_IWRITE);

    if(fd < 0){ 
        printf("\nshm_open error \n"); 
        return EXIT_FAILURE; 
    }
    fchmod(fd,S_IRWXU| S_IRWXG | S_IRWXO); 
    //Ensure the correct size is allocated 
    if (ftruncate(fd, sizeof(int))< 0){
        printf ("ftruncate error \n");
        return EXIT_FAILURE; 
    } 
    //addrPtr= (unsigned char *)mmap(NULL, sizeof(MemData), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 ); 
    addrPtr= (unsigned char *)mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 ); 
    if(addrPtr == MAP_FAILED){ 
        printf ("mmap error"); 
        return EXIT_FAILURE;
    }
    addrPtr[0]= 0;
    addrPtr[1]= 0;
    addrPtr[2]= 0;
    addrPtr[3]= 0; 
    //startReceive(); 
    munmap(addrPtr,sizeof(int));
    close(fd); 
    return 0;
}

0 个答案:

没有答案