2015-06-01 57 views
2

有沒有辦法創建一個「文件」(即在文件系統中的某個點),然後可以作爲常規文件打開任何程序,但讀取/寫入它將去一個程序而不是磁盤?命名管道似乎滿足所有要求,除了它只允許串行文件訪問。隨機訪問替代命名管道

我目前對* nix類型系統感興趣,但對於在任何操作系統/文件系統上聽到這樣的系統會感到好奇。

+0

要回答這個問題需要更多的信息。如下所述,mmap()可能是MIGHT worker,但前提是你有一個固定的文件大小。 – user3344003

回答

1

這裏是一個實現:

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; 
    for (i = 0; i != 10; ++i) { 
     addr[i] = '0' + i; 
    } 
    while (1) { 
     for (i = 0; i != 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; 
} 

我們從 「的/ dev/MEM」 10字節的內存映射到我們的惡魔程序。 cli以普通文件的形式打開這個文件,並在隨機地址中寫入一個字節。當然,你可以映射任何其他文件而不是/ dev/mem,但是你需要在mmap之前從常規文件'分配'一些字節。例如:

fd = open("/path/to/myfile", O_CREAT|O_RDWR, 0666); 
write(fd, "", 10); // 'allocate' 10 bytes from regular file 
addr = (char *)mmap(NULL, 10, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); 
0

可能你可以使用mmap來創建一個共享內存,後端程序擁有這個內存。其他程序可以打開這個'文件'並隨機讀/寫它到後端程序。

我還沒有嘗試,但我認爲它可以工作!