UNIX环境高级编程学习之第十五章进程间通信 - 两个进程通过映射普通文件实现共享内存通信 写数据进程 /* User:Lixiujie * Date:20100831 * Desc:两个进程通过映射普通文件实现共享内存通信 写数据进程 * File:map1.c * System:Ubuntu 64bit * gcc map1.c -o mapDemo1 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> typedef struct _People{ char szName[32]; int iAge; }People; int main(void){ int fd, i; People *p; char c = 'a'; /* 创建或打开一个空文件 */ fd = open("map.date", O_CREAT|O_RDWR|O_TRUNC, 00777); if (-1 == fd){ perror("main() open() is failed!/n"); exit(1); } /* 产生空洞 */ if (lseek(fd, sizeof(People)*5-1, SEEK_SET) == -1){ perror("main() lseek() is failed!/n"); close(fd); exit(1); } write(fd, "", 1); /* 映射文件创建共享内存 */ p = (People *)mmap(NULL, sizeof(People)*10, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (MAP_FAILED == p){ perror("main() mmap() is failed!/n"); close(fd); exit(1); } close(fd); /* 写入数据, 写入数据是文件大小的2倍, * 又因为没有超过超过文件大小整内存页大小,所以不会报错 * 否则 会收到SIGBUS信号 */ for (i=0;i<10;i++){ (*(p+i)).szName[0] = c+i; (*(p+i)).szName[1] = '/0'; (*(p+i)).iAge = 20 + i; } printf("main() map has data./n"); sleep(20); /* 会把数据写入文件,删除共享内存 */ munmap(p, sizeof(People)*10); printf("main() munmap() ok /n"); /* 此时再过会打开 读共享内存程序只有文件大小的数据。 */ return 0; } 读数据进程 /* User:Lixiujie * Date:20100831 * Desc:两个进程通过映射普通文件实现共享内存通信 读数据进程 * File:map2.c * System:Ubuntu 64bit * gcc map2.c -o mapDemo2 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> typedef struct _People{ char szName[32]; int iAge; }People; int main(void){ int fd, i; People *p; /*打开一个文件 */ fd = open("map.date", O_CREAT|O_RDWR, 00777); if (-1 == fd){ perror("main() open() is failed!/n"); exit(1); } p = (People*)mmap(NULL,sizeof(People)*10,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); if (MAP_FAILED == p){ perror("main() mmap() is failed!/n"); close(fd); exit(1); } close(fd); for (i=0;i<10;i++){ printf("Name=%s, Age=%d/n",(*(p+i)).szName, (*(p+i)).iAge); } munmap(p, sizeof(People)*10); return 0; }