如何为进程内部存储器创建外部文件系统只读入口点?

5 linux memory

目标平台是GNU/Linux


假设我有:

void *p
Run Code Online (Sandbox Code Playgroud)

我想在文件系统中为该内部存储器创建入口点,例如:

/tmp/my_entry_point
Run Code Online (Sandbox Code Playgroud)

我希望能够从另一个过程中读取该内存。

fd = open("/tmp/my_entry_point", ...)
read(fd, ...)
Run Code Online (Sandbox Code Playgroud)

是否可以创建和读取这样的伪设备?

der*_*ert 6

听起来您实际上是在描述 POSIX 共享内存。

这是一对快速的示例程序来展示它是如何工作的。在我的系统上,文件是在 /run/shm(这是一个 tmpfs)中创建的。其他系统使用 /dev/shm。你的程序不需要关心,shm_open会关心这个。

服务器.c:

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

int main() {
    int fd;
    long pagesize;
    char *region;

    if (-1 == (pagesize = sysconf(_SC_PAGE_SIZE))) {
        perror("sysconf _SC_PAGE_SIZE");
        exit(1);
    }

    if (-1 == (fd = shm_open("/some-name", O_CREAT|O_RDWR|O_EXCL, 0640))) {
        perror("shm_open");
        exit(1);
    }

    if (-1 == ftruncate(fd, pagesize)) {
        perror("ftruncate");
        shm_unlink("/some-name");
        exit(1);
    }

    region = mmap(NULL, pagesize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    if (!region) {
        perror("mmap");
        shm_unlink("/some-name");
        exit(1);
    }

    // PAGESIZE is guaranteed to be at least 1, so this is safe.
    region[0] = 'a';

    sleep(60);

    shm_unlink("/some-name");
}
Run Code Online (Sandbox Code Playgroud)

客户端

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

int main() {
    int fd;
    long pagesize;
    char *region;

    if (-1 == (pagesize = sysconf(_SC_PAGE_SIZE))) {
        perror("sysconf _SC_PAGE_SIZE");
        exit(1);
    }

    if (-1 == (fd = shm_open("/some-name", O_RDONLY, 0640))) {
        perror("shm_open");
        exit(1);
    }

    region = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
    if (!region) {
        perror("mmap");
        shm_unlink("/some-name");
        exit(1);
    }

    // PAGESIZE is guaranteed to be at least 1, so this is safe.
    printf("The character is '%c'\n", region[0]);
}
Run Code Online (Sandbox Code Playgroud)

生成文件

LDFLAGS += -lrt

all: server client
Run Code Online (Sandbox Code Playgroud)