實質上mmap是內核借助文件幫我們創建了一個映射區,多個進程之間利用該映射區完成數據傳遞。由于內核空間多進程共享,因此無血緣關系的進程間也可以使用mmap來完成通信。只要設置相應的標志位參數flags即可。若想實現共享,當然應該使用MAP_SHARED了。
// mmap_w.c??????
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>struct STU {int id;char name[20];char sex;
};void sys_err(char *str)
{perror(str);exit(1);
}int main(int argc, char *argv[])
{int fd;struct STU student = {10, "xiaoming", 'm'};struct STU *mm;if (argc < 2) {printf("./a.out file_shared\n");exit(-1);}fd = open(argv[1], O_RDWR | O_CREAT, 0664);ftruncate(fd, sizeof(student));mm = mmap(NULL, sizeof(student), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);if (mm == MAP_FAILED)sys_err("mmap");close(fd);while (1) {memcpy(mm, &student, sizeof(student));student.id++;sleep(1);}munmap(mm, sizeof(student));return 0;
}
// mmap_r.c
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>struct STU {int id;char name[20];char sex;
};void sys_err(char *str)
{perror(str);exit(-1);
}int main(int argc, char *argv[])
{int fd;struct STU student;struct STU *mm;if (argc < 2) {printf("./a.out file_shared\n");exit(-1);}fd = open(argv[1], O_RDONLY);if (fd == -1)sys_err("open error");mm = mmap(NULL, sizeof(student), PROT_READ, MAP_SHARED, fd, 0);if (mm == MAP_FAILED)sys_err("mmap error");close(fd);while (1) {printf("id=%d\tname=%s\t%c\n", mm->id, mm->name, mm->sex);sleep(2);}munmap(mm, sizeof(student));return 0;
}
結論:該方式與利用文件進行通信的方式相似,只是mmap更加簡單。只要映射的是同一個文件,且采用MAP_SHARED參數即可,這樣共享映射的空間。
strace命令。 strace ./test? 追蹤可執行文件test在程序執行過程中使用了哪些系統調用。