存储映射IO(二)
mmap父子進(jìn)程間通信
1. 測試代碼:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/wait.h>int var = 100;int main(void) {int *p;pid_t pid;int fd;fd = open("temp", O_RDWR | O_CREAT | O_TRUNC, 0644);if(fd < 0) {perror("open error");exit(1);}unlink("temp"); //刪除臨時(shí)文件目錄項(xiàng),使之具備被釋放條件ftruncate(fd, 4);p = (int *) mmap(NULL, 4, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);if(p == MAP_FAILED) {perror("mmap error");exit(1);}close(fd); //映射區(qū)建立完畢,即可關(guān)閉文件 pid = fork(); //創(chuàng)建子進(jìn)程 if(pid == 0) {*p = 2000;var = 1000;printf("child, *P = %d, var = %d\n", *p, var);} else {sleep(1);printf("parent, *p = %d, var = %d\n", *p, var);wait(NULL);int ret = munmap(p, 4); //釋放映射區(qū) if(ret == -1) {perror("munmap error");exit(1);}}return 0; }輸出結(jié)果:
?
2. 測試代碼:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/wait.h>int var = 100;int main(void) {int *p;pid_t pid;int fd;fd = open("temp", O_RDWR | O_CREAT | O_TRUNC, 0644);if(fd < 0) {perror("open error");exit(1);}unlink("temp"); //刪除臨時(shí)文件目錄項(xiàng),使之具備被釋放條件ftruncate(fd, 4);p = (int *) mmap(NULL, 4, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);if(p == MAP_FAILED) {perror("mmap error");exit(1);}close(fd); //映射區(qū)建立完畢,即可關(guān)閉文件 pid = fork(); //創(chuàng)建子進(jìn)程 if(pid == 0) {*p = 2000;var = 1000;printf("child, *P = %d, var = %d\n", *p, var);} else {sleep(1);printf("parent, *p = %d, var = %d\n", *p, var);wait(NULL);int ret = munmap(p, 4); //釋放映射區(qū) if(ret == -1) {perror("munmap error");exit(1);}}return 0; }輸出結(jié)果:
總結(jié)
- 上一篇: lol卡牌大师是短手英雄还是长手英雄
- 下一篇: 命令新参