2014-03-28 49 views
1

我有服務器,使用多個進程(fork())。數據塊很大,可以由一個進程創建,應該在其他進程之間共享。linux上的進程之間共享內存

因此,我使用shm_open + mmap來創建共享內存並將其映射到虛擬內存。

struct SharedData { 
    const char *name; 
    int descriptor; 
    void *bytes; 
    size_t nbytes; 
} 

void shared_open(SharedData *data, const char *name, size_t nbytes) { 
    int d = shm_open(name, O_RDONLY, S_IRUSR | S_IWUSR); 
    if (d != -1) { 
     void *bytes = mmap(NULL, nbytes, PROT_READ, MAP_SHARED, d, 0); 
     data->name = name; 
     data->descriptor = d; 
     data->bytes = bytes; 
     data->nbytes = nbytes; 
    } else { 
     data->descriptor = -1; 
    } 
} 

void shared_create(SharedData *data, const char *name, void *bytes, size_t nbytes) { 
    int d = shm_open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); 
    if (d != -1) { 
     if (nbytes = write(d, bytes, nbytes)) { 
      shared_open(data, name, nbytes); 
     } 
     shm_unlink(name); 
    } 
} 

void shared_close(SharedData *data) { 
    if (data->descriptor != -1) { 
     munmap(data->bytes, data->nbytes); 
     shm_unlink(data->name); 
    } 
} 

初始過程中創建共享內存對象與shared_create,其他進程shared_open

是這種方法有效打開呢?有更有效或更簡單的方法嗎?

+0

您是否知道'fork'使用copy-on-write策略?內存頁面是共享的,直到其中一個進程修改它? – zch

+0

只有一個進程可以創建共享數據,它只能讀取其他進程。共享數據只能在fork階段後才能創建 – SBKarr

+0

您是否對實現代碼有特定的問題?如果不是,您的問題屬於[代碼評論](http://codereview.stackexchange.com/)站點。 –

回答