共享記憶體在無血緣關係程序間通訊
匿名對映
類unix
/*
* function: 演示使用mmap()函式實現使用共享對映區完成父子程序間通訊
* * 2020-12-07
*/#include
#include
#include
#include
#include
#include
intmain
(int argc,
char
*ar**)
// 擴充套件檔案大小, 需要開啟的檔案具有可寫屬性if(
ftruncate
(fd,20)
==-1)
// 獲取檔案大小
off_t n =
lseek
(fd,0,
seek_end);
if(n ==-1
)// 將檔案對映到共享記憶體中
char
*p =
null
; p =
(char*)
mmap
(null
, n, prot_read | prot_write, map_shared, fd,0)
;if(p == map_failed)
pid_t pid =0;
pid =
fork()
;if(pid ==-1
)else
if(pid ==0)
// 子程序
else
// 父程序
// 系統呼叫刪除指定位址範圍的對映if(
* function: 演示使用mmap()函式實現使用共享對映區完成無血緣關係程序間通訊
* 此程序為寫端
* * 2020-12-07
*/#include
#include
#include
#include
#include
#include
intmain
(int argc,
char
*ar**)
// 擴充套件檔案大小, 需要開啟的檔案具有可寫屬性if(
ftruncate
(fd,20)
==-1)
// 獲取檔案大小
off_t n =
lseek
(fd,0,
seek_end);
if(n ==-1
)// 將檔案對映到共享記憶體中
char
*p =
null
; p =
(char*)
mmap
(null
, n, prot_read | prot_write, map_shared, fd,0)
;if(p == map_failed)
// 寫共享記憶體
strcpy
(p,"hello world");
printf
("寫共享記憶體完成\n");
// 系統呼叫刪除指定位址範圍的對映if(
munmap
(p, n)==-
1)close
(fd)
;return0;
}
只能用於有血緣關係程序間通訊/*
* function: 演示使用mmap()函式實現使用共享對映區完成無血緣關係程序間通訊
* 此程序為讀端
* 2020-12-07
*/#include
#include
#include
#include
#include
#include
intmain
(int argc,
char
*ar**)
// 獲取檔案大小
off_t n =
lseek
(fd,0,
seek_end);
if(n ==-1
)// 將檔案對映到共享記憶體中
char
*p =
null
; p =
(char*)
mmap
(null
, n, prot_read | prot_write, map_shared, fd,0)
;if(p == map_failed)
// 讀共享記憶體
printf
("%s\n"
, p)
;printf
("讀共享記憶體完成\n");
// 系統呼叫刪除指定位址範圍的對映if(
munmap
(p, n)==-
1)close
(fd)
;return0;
}
通過mmap函式第4個引數,使用map_anonymous (或 map_anon)完成匿名對映。
map_anonymous 和 map_anon 這兩個巨集是 linux 作業系統特有的巨集。在類 unix 系統中如無該巨集定義,可通過/dev/zero檔案完成匿名對映。/*
* function: 演示使用mmap()函式實現匿名對映完成父子程序間通訊
* * 2020-12-08
*/#include
#include
#include
#include
#include
#include
intmain
(int argc,
char
*ar**)
pid_t pid =0;
pid =
fork()
;if(pid ==-1
)else
if(pid ==0)
// 子程序
else
// 父程序
// 系統呼叫刪除指定位址範圍的對映if(
munmap
(p, n)==-
1)return0;
}
/*
* function: 演示使用mmap()函式實現使用共享對映區完成父子程序間通訊
* * 2020-12-07
*/#include
#include
#include
#include
#include
#include
intmain
(int argc,
char
*ar**)
// 將檔案對映到共享記憶體中
char
*p =
null
; size_t n =
10;
p =(char*)
mmap
(null
, n, prot_read | prot_write, map_shared, fd,0)
;if(p == map_failed)
pid_t pid =0;
pid =
fork()
;if(pid ==-1
)else
if(pid ==0)
// 子程序
else
// 父程序
// 系統呼叫刪除指定位址範圍的對映if(
程序間通訊 共享記憶體
下面是自己寫的乙個簡單的共享記憶體的程序間通訊的例子。共享記憶體是用於程序間大量資料共享的一種方法。include include include include include include int main if buf1 shmat shmid,0,0 void 1 strcpy buf1,...
程序間通訊 共享記憶體
共享記憶體是被多個程序共享的一部分物理記憶體。共享記憶體是程序間共享資料的一種最快的方式,乙個程序向共享記憶體區域寫入資料,共享這個記憶體區域的所有程序就可以立刻看到其中的內容。共享記憶體實現分兩個步驟 建立共享記憶體,使用shmget函式 對映共享記憶體,使用shmat函式 共享記憶體是一種最為高...
程序間通訊 共享記憶體
共享記憶體允許兩個或更多程序共享一塊給定的儲存區,因為資料不需要在不同程序之間訪問,這是最快的一種ipc 傳輸資訊量很大,通過記憶體空間對映程序空間實現,若伺服器程序正在將資料放入共享儲存區,則在它做完這一操作之前,客戶程序不應取這些資料,通常訊號量用來實現對共享儲存訪問的同步。核心為每個共享儲存段...