示例:
#include <sys/mman.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> int main(int argc,char **argv) { int ret, inum = 0; #if 0 // 该段用匿名映射区代替 int fd = open("mytest.txt", O_CREAT|O_RDWR, 0644); if(fd < 0) { perror("open feild!"); return -1; } ret = ftruncate(fd, 4); if(ret == -1) { perror("ftruncate feild!"); return -1; } char *ptr = mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if(ptr == MAP_FAILED) { perror("mmap feild!"); return -1; } close(fd); #else char *ptr = mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); if(ptr == MAP_FAILED) { perror("mmap feild!"); return -1; } #endif *(int *)ptr = 1234; printf("ptr : %d, inum : %d\n", *(int *)ptr, inum); pid_t pid = fork(); if(pid == 0) // son { *(int *)ptr = 5678; inum = 6666; printf("ptr : %d, inum : %d\n", *(int *)ptr, inum); } if(pid > 0) // father { wait(NULL); printf("ptr : %d, inum : %d\n", *(int *)ptr, inum); ret = munmap(ptr, 4); if(ret == -1) { perror("munmap feild!"); return -1; } } return 0; }
标签:基本,return,int,mmap,用法,inum,include,ptr From: https://www.cnblogs.com/yinguojin/p/17482495.html