mmap小示例

 

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define TRUE        1
#define FALSE       -1
#define FILE_SIZE   100

#define MMAP_FILE_PATH "./mmap.txt"

size_t get_file_size(const char* file_path)
{
    struct stat buf;
    if(stat(file_path, &buf)<0)
    {
        printf("%s[%d]:%s",__FUNCTION__,__LINE__,strerror(errno));
        return -1;
    }
    return buf.st_size;
}


int main(int argc, char** argv)
{
    int fd = -1;
    //char buff[100]={0};
    void *result;    
    int lseek_result = -1;
    int file_length = -1;
    
    // 1. open the file 
    fd = open(MMAP_FILE_PATH,O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
    if( -1==fd)
    {
        printf("open failed \n");
        printf("%s\n", strerror(errno));
        return FALSE;
    }
    
    //2. adjust the file size
    lseek_result = lseek(fd, FILE_SIZE-1, SEEK_SET);
    if( -1 == lseek_result)
    {
       printf("lseek failed\n");
       printf("%s\n", strerror(errno));
       return FALSE;
    }
    write(fd,"\0",1);
    lseek(fd,0,SEEK_SET);
    
    //3. get the filesize
    file_length = get_file_size(MMAP_FILE_PATH);
    if(-1 == file_length)
    {
       printf("get file size failed \n");
       return FALSE;
    }
    printf("filesize = %d\n",file_length);
    
    //4. call mmap
    result = mmap(0, file_length, \
                 PROT_READ|PROT_WRITE,\
		 MAP_SHARED,\
		 fd,0);
    if( result == (void*)-1)
    {
        printf("mmap failed\n");
        printf("%s\n", strerror(errno));
        return FALSE;
    }
    
    //5. release the file descriptor
    close(fd);

    //6. write something to mmap addr,
    strncpy(result, "hello world\n",file_length);
       
    //7. call munmap
    munmap(0, file_length);

    return 0;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值