四、网上测试实例
(1)demo1 演示一下,将文件/tmp/file_mmap中的字符转成大写,分别使用mmap与read/write二种方法实现。 先创建/tmp/file_mmap文件,该文件写入www.baidu.com,使用strace统计系统调用。
/*
- @file: t_mmap.c
*/
#include <stdio.h>
#include <ctype.h>
#include <sys/mman.h> /mmap munmap/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd;
char *buf;
off_t len;
struct stat sb;
char *fname = “/tmp/file_mmap”;
fd = open(fname, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1)
{
perror(“open”);
return 1;
}
if (fstat(fd, &sb) == -1)
{
perror(“fstat”);
return 1;
}
buf = mmap(0, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (buf == MAP_FAILED)
{
perror(“mmap”);
return 1;
}
if (close(fd) == -1)
{
perror(“close”);
return 1;
}
for (len = 0; len < sb.st_size; ++len)
{
buf[len] = toupper(buf[len]);
/putchar(buf[len]);/
}
if (munmap(buf, sb.st_size) == -1)
{
perror(“munmap”);
return 1;
}
return 0;
}
自己测试运行结果:
root@chenwr-pc:/home/workspace/test# gcc tmp.c -o run
root@chenwr-pc:/home/workspace/test# strace ./run
execve("./run", ["./run"], [/* 22 vars */]) = 0
brk(0) = 0x1ffa000
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=106932, …}) = 0
mmap(NULL, 106932, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fcab05de000
close(3) = 0
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, “\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0P \2\0