建立乙個讀檔案 mmap_r.c
#include
#include
#include
#include
#include
#include
#include
struct stu
;void
sys_err
(char
*str)
intmain
(int argc,
char
*ar**)
fd =
open
(ar**[1]
,o_rdonly);if
(fd ==-1
)sys_err
("open error");
mm =
mmap
(null
,sizeof
(student)
,prot_read,map_shared,fd,0)
;if(mm == map_failed)
sys_err
("mmap error");
close
(fd)
;while(1
)munmap
(mm,
sizeof
(student));
return0;
}
建立乙個寫檔案 mmap_w.c
#include
#include
#include
#include
#include
#include
#include
struct stu
;void
sys_err
(char
*str)
intmain
(int argc,
char
*ar**)
;struct stu *mm;
if(argc <2)
fd =
open
(ar**[1]
,o_rdwr | o_creat,
0664);
ftruncate
(fd,
sizeof
(student));
mm =
mmap
(null
,sizeof
(student)
, prot_read|prot_write, map_shared, fd,0)
;if(mm == map_failed)
sys_err
("mmap error");
close
(fd)
;while(1
)munmap
(mm,
sizeof
(student));
return0;
}
建立乙個共享檔案 file_shared
1.分別編譯兩個檔案
2.先執行寫檔案 ./mmap_w file_shared
3.再開啟乙個終端,執行讀檔案 ./mmap_r file_shared
從結果可以看出,寫端一直在覆蓋原來的id,讀端一直在讀取file_shared中的內容。
程序間通訊 mmap
void mmap void addr,size t length,int prot,int flags,int fd,off t offset 建立共享記憶體對映 引數 addr 指定對映區的首位址。通常傳null,表示讓系統自動分配 length 共享記憶體對映區的大小。檔案的實際大小 prot...
Linux 程序間通訊 mmap
讀操作 include include include include include include include struct ad struct ad ptr intmain int argc,char ar while 1 printf n for int i 0 i 5 i printf...
程序間通訊之記憶體對映 mmap記憶體對映
讀資料端程序 mmanp r.c include include include include include include define len 0x1000 int main close fd while 1 close fd munmap addr,len return 0 寫資料端程序 ...