対象プラットフォームはGNU/Linux。
私が持っているとしましょう:
void *p
ファイルシステム内の内部メモリのエントリポイントを作成したいと思います。たとえば、次のようになります。
/tmp/my_entry_point
その記憶を読むことができたらいいのに他のプロセス内で。
fd = open("/tmp/my_entry_point", ...)
read(fd, ...)
そのような疑似デバイスを作成して読むことは可能ですか?
ベストアンサー1
実際には、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");
}
クライアント.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_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]);
}
ファイルの生成
LDFLAGS += -lrt
all: server client