Linux程序共享通訊 mmap實現

2021-09-08 14:07:48 字數 1911 閱讀 3342

使用mmap記憶體對映實現一端寫,另一端讀的程序間通訊

寫端**write.c

/*write.c*/

#include #include #include #include #include #include #include /*對映記憶體大小*/ #define maplen 0x100 /*定義乙個學生資訊結構體*/ struct stu ; /*出錯資訊統一處理函式*/ void sys_err(char *str, int exitno) int main(int argc, char*ar**) fd = open(ar**[1], o_rdwr | o_creat, 0777); //開啟一檔案 if(fd < 0) if(lseek(fd, maplen - 1, seek_set) < 0) if(write(fd, "\0", 1) < 0) /*將檔案對映至程序的位址空間*/ pm = mmap(null, maplen, prot_read | prot_write, map_shared, fd, 0); if(pm == map_failed) /*關閉檔案描述符*/ close(fd); /*對檔案進行寫入操作*/ while(1)else i++; sleep(1); } munmap(pm, maplen); return 0; }

讀端**read.c

/*read.c*/

#include #include #include #include #include #include #include #define manlen 0x1000 struct stu ; void sys_err(char *str, int exitno) int main(int argc, char *ar**) fd = open(ar**[1], o_rdwr); if (fd < 0) pm = mmap(null, maplen, prot_read | prot_write, map_shared, fd, 0); if(pm == map_failed) /*關閉檔案*/ close(fd); /*刪除檔案*/ unlink(ar**[1]); /*在記憶體中讀資料*/ while(1) munmap(pm, maplen); return 0; }

執行過程:

yu@ubuntu:~/linux/211/tongxin$ ls

read.c write.c

yu@ubuntu:~/linux/211/tongxin$ gcc -o write write.c yu@ubuntu:~/linux/211/tongxin$ gcc -o read read.c yu@ubuntu:~/linux/211/tongxin$ ls read read.c write write.c

此時執行寫操作

yu@ubuntu:~/linux/211/tongxin$ ./write myfile

//在向myfile檔案中寫資料

另開一終端到當前目錄,執行如下讀操作:

yu@ubuntu:~/linux/211/tongxin$ ls

read read.c write write.c myfile

yu@ubuntu:~/linux/211/tongxin$ ./read myfile 6 yu-6 m 7 yu-7 w ^c//讀取寫入的內容ctrl+c退出

退出後,執行ls,可發現myfile檔案已刪除

yu@ubuntu:~/linux/211/tongxin$ ls

read read.c write write.c

程序通訊 mmap記憶體共享

回頁首if fd 0 回頁首 include include include include typedef structpeople main int argc,char argv map a normal file as shared mem printf initialize over n s...

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...

linux程序間記憶體共享 mmap

系統呼叫mmap 用於共享記憶體的兩種方式 1 使用普通檔案提供的記憶體對映 適用於任何程序之間 此時,需要開啟或建立乙個檔案,然後再呼叫mmap 典型呼叫 如下 fd open name,flag,mode if fd 0 ptr mmap null,len prot read prot writ...