mmap进程间通信
mmap进程间通信
写端
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> // 数据结构体 typedef struct { int pid; char Msg[20]; }DATA_T; int main(void) { /* 打开映射文件 */ int fd = open("mapfiles", O_RDWR); /* 扩展空文件 */ ftruncate(fd, sizeof(DATA_T)); /* 进行共享映射, 创建映射内存 */ DATA_T * p = mmap(NULL, sizeof(DATA_T), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); /* 向映射内存中持续写入 */ bzero(p, sizeof(DATA_T)); p->pid = getpid(); int i = 0; while (1) { sprintf(p->Msg, "%d:pid:%d\n", i, p->pid); i++; } return 0; }
读端
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> // 数据结构体 typedef struct { int pid; char Msg[20]; }DATA_T; int main(void) { /* 打开映射文件 */ int fd = open("mapfiles", O_RDWR); /* 进行共享映射, 创建映射内存 */ DATA_T * p = mmap(NULL, sizeof(DATA_T), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); while (1) { printf("%s", p->Msg); } return 0; }