依睛(IT blog) 我回来了,PHP<-->C/C++ LINUX

笨鸟

统计

积分与排名

友情连接

最新评论

用mmap()共享内存(转)

用mmap()共享内存

rurutia posted @ 2007年04月27日 11:48PM in 编程笔记 with tags 共享内存mmap
用python解析html

接口:

void *mmap( void *start, size_t length, int port, int flags, int fd, off_t offset)

正常返 回映射区的地址,出错返回-1。

start 为映射区域的首地址,一般赋 值NULL通过系统自动分配。

length 为区域大小。

fd 为映射文件的文件描述符。

offset 为映 射文件的偏移,也就是从文件的offset处开始映射。

port : 映射 区域的属性值,可取PORT_EXEC, PORT_READ, PORT_WRITE, PORT_NONE,四个值,分别 是区域内可执行、可读、可写和不可访问。

flags : 映射文件属 性值,可取 MAP_ANON, MAP_PRIVATE, MAP_SHARED,分别代表匿名映射,私有copy-on -write映射,和共享映射。

MAP_ANON映射只能实现父子进程的内存共 享,因为只有父子进程有才有相同的映射后的地址空间,不同进程的内存共享需要用 MAP_SHARED通过映射文件来实现。

值得一提的是,映射的初期并没有 真正分配内存,只有访问页面的时候,引发一个缺页异常,这时才真正分配内存。

示例a.c和b.c,先建立一个文件sharefile,内容是”My name is Foo!”。

----a.c----
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()


{
int fd;
char *prt;
char *msg="My name is Foo!";


fd=open("sharefile",O_RDWR,00777);
prt=(char*) mmap(NULL,strlen(msg)+1,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
close(fd);

memcpy(prt,msg,strlen(msg)+1);

printf("%s",prt);

sleep(10); /*等待b去修改共享内存内容。*/

printf("%s",prt);

munmap(prt,strlen(msg)+1);

return 0;
}

----b.c----

#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;
char *prt;


char *msg="My name is Bar!";
fd=open("sharefile",O_RDWR,00777);
prt=(char*) mmap(NULL,strlen(msg)+1,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
close(fd);

memcpy(prt,msg,strlen(msg)+1);

munmap(prt,strlen(msg));

return 0;
}

运行./a 程序输出:

My name is Foo!

停止10s

My name is Foo!

先运行./a, 然后切换另一个控制台运行./b,切换回发现a的输出变为:

						My name is Foo!
				

停止10s

						My name is Bar!
				

可见,a内 存中的内容被b修改了~最后的munmap函数会使得映射内存中的内容写回文件中,所以 文件中的内容也变成”My name is Bar!”。

参考资料: 1. 《Computer Systems - A Programmer's Perspective》 2.《Linux Programming by Example》

posted on 2008-11-13 12:25 向左向右走 阅读(1947) 评论(1)  编辑 收藏 引用 所属分类: C/C++学习资料库Linux 学习库

评论

# re: 用mmap()共享内存(转) 2013-09-13 17:31 zsf


会提示如下错误:
Bus error (core dumped)
  回复  更多评论   

只有注册用户登录后才能发表评论。