operating system - Random access alternative to named pipes -
is there way create "file" (i.e. point in file system) can opened program regular file, reading/writing go program instead of disk? named pipe seems meet requirements, except allows serial file access.
i interested in *nix type systems, curious hear of such system on os/file system.
here implementation:
demon.c:
#include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <unistd.h> #include <fcntl.h> #include <assert.h> #include <string.h> #include <errno.h> void map_file(const char *f) { int fd = open(f, o_creat|o_rdwr, 0666); if (fd < 0) { perror("fd open error\n"); exit(-1); } char *addr = (char *)mmap(null, 10, prot_read | prot_write, map_shared, fd, 0); if (addr == map_failed) { exit(-1); } int i; (i = 0; != 10; ++i) { addr[i] = '0' + i; } while (1) { (i = 0; != 10; ++i) { if (addr[i] != '0' + i) { printf("addr[%d]: %c\n", i, addr[i]); } } sleep(1); } } int main() { map_file("/dev/mem"); return 0; }
cli.c:
#include <sys/mman.h> #include <assert.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int main() { const char *f = "/dev/mem"; int fd = open(f, o_rdwr, 0666); assert(fd >= 0); lseek(fd, rand() % 10, seek_set); write(fd, "x", 1); close(fd); return 0; }
we map 10 bytes memory "/dev/mem" our demon program. cli open file regular file, , write byte in random address. of course, can map other file instead of /dev/mem, need 'alloc' byte regular file before mmap. eg:
fd = open("/path/to/myfile", o_creat|o_rdwr, 0666); write(fd, "0123456789", 10); // 'allocate' 10 bytes regular file addr = (char *)mmap(null, 10, prot_read|prot_write, map_shared, fd, 0);
Comments
Post a Comment