panda@panda-G31M-ES2C:~/code/c$ cat m_map.c
#include
#include
#include /*提供类型pid_t,size_t的定义*/
#include
#include
#include
int main(void)
{
int fd;
char *buf = NULL;
int i;
//打开一个文件
if (-1 == (fd = open("mapping_file.txt",O_RDWR,0)))
{
printf("open file error!\n");
exit(1);
}
//将文件映射到进程的一个内存区域
buf = mmap(NULL, 100, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (!buf)
{
printf("mmap error!\n");
exit(1);
}
//对映射内存读数据
for (i = 0; i < 100; i++)
printf("%c", buf[i]);
//对映射内存写数据
if (buf[0] == 'H')
buf[0] = 'h';
else
buf[0] = 'H';
system("cat mapping_file.txt");
return 0;
}
panda@panda-G31M-ES2C:~/code/c$ ./m_map
Hello world
hello world
代码运行无误,仔细看看就会理解了
阅读(2036) | 评论(1) | 转发(0) |