共享記憶體區

2021-06-22 02:33:46 字數 3575 閱讀 4600

共享記憶體區是最快的ipc形式。一旦這樣的記憶體對映到共享它的程序的位址空間,這些程序間資料傳遞不再涉及到核心,換句話說是程序不再通過執行進入核心的系統呼叫來傳遞彼此的資料。

mmap

函式

功能:將檔案或者裝置空間對映到共享記憶體區。

原型void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset);

引數addr: 要對映的起始位址,通常指定為null,讓核心自動選擇

len:對映到程序位址空間的位元組數

prot:對映區保護方式

flags:標誌

fd:檔案描述符

offset:從檔案頭開始的偏移量

prot

說明

prot_read

頁面可讀

prot_write

頁面可寫

proc_exec

頁面可執行

prot_none

頁面不可訪問

flags

說明

map_shared

變動是共享的

map_private

變動是私有的

map_fixed

準確解釋addr引數

map_anonymous

建立匿名對映區,不涉及檔案

munmap

函式

功能:取消mmap函式建立的對映

原型int munmap(void *addr, size_t len);

引數addr: 對映的記憶體起始位址

len:對映到程序位址空間的位元組數

返回值:成功返回0;失敗返回-1

msync

函式

功能:對對映的共享記憶體執行同步操作

原型int msync(void *addr, size_t len, int flags);

引數addr: 記憶體起始位址

len:長度

flags:選項

返回值:成功返回0;失敗返回-1

flags

說明

ms_async

執行非同步寫

ms_sync

執行同步寫

ms_invalidate

使快取記憶體的資料失效

map

注意點

對映不能改變檔案的大小

可用於程序間通訊的有效位址空間不完全受限於被對映檔案的大小

檔案一旦被對映後,所有對對映區域的訪問實際上是對記憶體區域的訪問。對映區域內容寫回檔案時,所寫內容不能超過檔案的大小。

nmap_read.c

#include

#include

#include

#include

#include

#include

#include

#include

#include

#define err_exit(m) \

do \

while(0)

typedef struct stu

stu;

int main(int argc, char *argv)

int fd;

fd = open(argv[1], o_rdwr);

if (fd == -1)

err_exit("open");

stu *p;

p = (stu*)mmap(null, sizeof(stu)*5, prot_read | prot_write, map_shared, fd, 0);

if (p == null)

err_exit("mmap");

int i;

for (i=0; i<10; i++)

munmap(p, sizeof(stu)*10);

printf("exit ...\n");

return 0;

}

nmap_write.c

#include

#include

#include

#include

#include

#include

#include

#include

#include

#define err_exit(m) \

do \

while(0)

typedef struct stu

stu;

int main(int argc, char *argv)

int fd;

fd = open(argv[1], o_creat | o_rdwr | o_trunc, 0666);

if (fd == -1)

err_exit("open");

lseek(fd, sizeof(stu)*5-1, seek_set);

write(fd, "", 1);

stu *p;

p = (stu*)mmap(null, sizeof(stu)*10, prot_read | prot_write, map_shared, fd, 0);

if (p == null)

err_exit("mmap");

char ch = 'a';

int i;

for (i=0; i<10; i++)

printf("initialize over\n");

sleep(10);

munmap(p, sizeof(stu)*10);

printf("exit ...\n");

return 0;

}

makefile:

.phony:clean all

cc=gcc

cflags=-wall -g

bin=mmap_write mmap_read

all:$(bin)

%.o:%.c

$(cc) $(cflags) -c $< -o $@

clean:

rm -f *.o $(bin)

共享記憶體區

一 什麼是共享記憶體區 共享記憶體區是最快的可用ipc形式。它允許多個不相關的程序去訪問同一部分邏輯記憶體。如果需要在兩個執行中的程序之間傳輸資料,共享記憶體將是一種效率極高的解決方案。一旦這樣的記憶體區對映到共享它的程序的位址空間,這些程序間資料的傳輸就不再涉及核心。這樣就可以減少系統呼叫時間,提...

Posix共享記憶體區

1 概述 posix提供了兩種在無親緣關係程序間共享記憶體區的方法 者兩種方法多需要呼叫mmap,差別在於作為mmap的引數之一的描述符的獲取手段。2 posix共享記憶體區物件 posix共享記憶體區涉及以下兩個步驟要求 1 指定乙個名字引數呼叫shm open,以建立乙個新的共享記憶體區物件或開...

System V 共享記憶體區

system v共享記憶體區在概念上類似於posix共享記憶體區。代之以呼叫shm open後呼叫mmap的是,先呼叫shmget,再呼叫shmat函式。shmget函式建立乙個尚未存在的共享記憶體區,或者訪問乙個已經存在的共享記憶體區。include int shmget key t key,si...