进程间通信-mmap

要想使用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;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值