要想使用mmap实现进程间的通信,首先得去了解该函数.
该函数有6个参数,可能以前没有见过这么多参数的函数原型,要想深入理解这些参数的意义,我们得需要了解mmap工作的原理。
第一个为进程空间中内存地址的起始地址,第二个参数为在内存中的长度,第三个参数为执行的权限,第四个参数为内存映射的方式,第五个参数与为文件描述符,第六个参数与 为文件的偏移量。
那么有一个问题便是,我们在进行进程间的通信,是通过文件来进行的,要经过实际的io操作,速率是否会很低下。实际上不会,操作系统会采用一种缓输出机制,当操作系统发现内核中有文件得数据时,会直接从中读取。
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #define MAXSIZE 100 void sys_err(const char *str,int exitno) { perror(str); exit(exitno); } int main(int argc,char *argv[]) { char* mm; if(argc!=2) { printf("./a.out filename\n"); return ; } int fd; fd = open(argv[1],O_RDWR|O_CREAT,0777); if(fd<0) sys_err("open",1); if(lseek(fd,MAXSIZE-1,SEEK_SET)<0) sys_err("lseek",2); if(write(fd,"\0",1)<0) sys_err("write",3); mm = mmap(NULL,MAXSIZE,PROT_WRITE|PROT_READ,MAP_SHARED,fd,0); if(mm == MAP_FAILED) sys_err("mmap",2); close(fd); sprintf(mm,"pid %d too young to simple\n",getpid()); munmap(NULL,MAXSIZE); return 0; } #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/mman.h> #define MAXSIZE 100 void sys_err(const char *str,int exitno) { perror(str); exit(exitno); } int main(int argc,char *argv[]) { char* mm; if(argc!=2) { printf("./a.out filename\n"); return ; } int fd; fd = open(argv[1],O_RDWR); if(fd<0) sys_err("open",1); mm = mmap(NULL,MAXSIZE,PROT_WRITE|PROT_READ,MAP_SHARED,fd,0); if(mm == MAP_FAILED) sys_err("mmap",2); close(fd); write(STDOUT_FILENO,mm,strlen(mm)); munmap(NULL,MAXSIZE); return 0; }