Summary

一种进程间通信的实现方式

服务端

#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
 
int main(int argc, char const *argv[]) {
    //man shm_open看看更多相关内容
    int fd = shm_open("test", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if (fd < 0) {
        printf("error");
        return 1;
    }
    ftruncate(fd, 100); //设置共享内存大小
    char *a = mmap(NULL, 100, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    memcpy(a, argv[1], strlen(argv[1]) + 1);
    printf("%s\n", a);
    sleep(10);
    shm_unlink("test"); // 关闭共享内存
    return 0;
}
 

客户端

#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
 
int main(int argc, char const *argv[]) {
    int fd = shm_open("test", O_RDONLY, S_IRUSR | S_IWUSR);
    if (fd < 0) {
        printf("error");
        return 1;
    }
    ftruncate(fd, 100);
    char *a = mmap(NULL, 100, PROT_READ, MAP_SHARED, fd, 0);
    printf("%s\n", a);
    return 0;
}
 

Note

在使用cmake组织代码时, 需要target_link_libraries(${your_app} rt)才能正常链接

相关函数

NAME shm_open, shm_unlink - create/open or unlink POSIX shared memory objects

SYNOPSIS

#include <sys/mman.h>
#include <sys/stat.h>        /* For mode constants */
#include <fcntl. h>           /* For O_* constants */
 
int shm_open(const char *name, int oflag, mode_t mode);
int shm_unlink(const char *name);
 
//Link with -lrt.

MORE

​ 查看manual,在有些系统中,客户端想访问服务端创建的共享内存,需要申请特定的权限