本文共 1727 字,大约阅读时间需要 5 分钟。
#include#include #include #include #include #include #include #include typedef struct Student { int id; char name[64]; int age;} student;void sys_err(const char *str) { perror(str); exit(1);}int main(void) { struct student stu = {1, "xiaoming", 18}; struct student *p = NULL; int fd; fd = open("test_map", O_RDWR | O_CREAT | O_TRUNC, 0664); if (fd == -1) { sys_err("open failed."); } ftruncate(fd, sizeof(stu)); p = mmap(NULL, sizeof(stu), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { sys_err("mmap error"); } close(fd); while (1) { memcpy(p, &stu, sizeof(stu)); stu.id++; } munmap(p, sizeof(stu)); return 0;}
#include#include #include #include #include #include #include #include typedef struct Student { int id; char name[64]; int age;} student;void sys_err(const char *str) { perror(str); exit(1);}int main(void) { struct student stu; struct student *p = NULL; int fd; fd = open("test_map", O_RDONLY, 0664); if (fd == -1) { sys_err("open failed."); } p = mmap(NULL, sizeof(stu), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { sys_err("mmap error"); } close(fd); while (1) { printf("id=%d, name=%s, age=%d\n", p->id, p->name, p->age); } munmap(p, sizeof(stu)); return 0;}
由于我们开辟的映射区刚好是一个stu的大小,可能会因为读取速度较慢而导致前面的一些student类型数据被覆盖。
将写程序的open命令去掉O_TRUNC标志,确保多个进程在写入时文件可以追加。
1)多个进程写入单个读者可以看到,mmap允许重复读取,因为文件内容不会改变。而使用管道(pipe)和首次入先出(fifo)则不同,管道中的数据一读就丢失。
pipe和fifo只能读取一次。pipe和fifo则依赖于共享的管道。从这个角度来看,fifo也可以看作是无血缘通信的一种实现方式。转载地址:http://osfv.baihongyu.com/