目标平台是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)
是否可以创建和读取这样的伪设备?
听起来您实际上是在描述 POSIX 共享内存。
这是一对快速的示例程序来展示它是如何工作的。在我的系统上,文件是在 /run/shm(这是一个 tmpfs)中创建的。其他系统使用 /dev/shm。你的程序不需要关心,shm_open会关心这个。
#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)
| 归档时间: |
|
| 查看次数: |
302 次 |
| 最近记录: |