先启动进程1,输入字符,在进程2就会不停显示进程1的输入字符。数据是通过内存来传递的。fd文件映射到内存后是关闭的。
经试验,fd文件必须先存在,而且不能为空,也就是说不能把空文件映射到内存
文件的读写权限必须和mmap 映射的类型一致
mmap 返回指针类型必须和文件中类型一致。文件是文本类型,mmap 指针必须是char,fd文件存储的是int ,mmap指针就是int,甚至是struct 结构数据
此文件可以是linux硬件性文件,如/ dev/vedio
这也是mmap另一个功能,把硬件映射到内存。
进程1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <wait.h>
#include <signal.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(void){
int fd=open("/home/wjs/1.txt",O_RDWR);
char *p=mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
printf("%s","start:");
while(1){
char c[20];
scanf("%s",c);
strcpy(p,c);
}
return 0;
}
进程2:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <wait.h>
#include <signal.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(void){
int fd=open("/home/wjs/1.txt",O_RDWR);
char *p=mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
printf("%s","js:");
close(fd);
while(1){
printf("%s\n",p);
sleep(3);
}
return 0;
}