zoukankan      html  css  js  c++  java
  • memcpy和mmap

       1:  /*
       2:  author:justinzhang
       3:  email:uestczhangchao@gmail.com
       4:  time:2012-8-22 18:50:23:
       5:  desc: a buggy program from bbs.qshpan.com, i use strerror(errno) to locate
       6:  the problem, the problem is that i didn't give the second command line arguments.
       7:   After making it running properly, i add some exception handling code:)                
       8:  */
       9:  #include<errno.h>
      10:  #include<sys/mman.h> 
      11:  #include<sys/types.h> 
      12:  #include<fcntl.h> 
      13:  #include<unistd.h> 
      14:  #include<string.h> 
      15:  #include<stdio.h>
      16:  #include<sys/stat.h>
      17:  #include<stdlib.h>
      18:  typedef struct 
      19:  { 
      20:    char name[4]; 
      21:    int age; 
      22:  }people; 
      23:  main(int argc,char** argv) 
      24:  { 
      25:     int fd ,i; 
      26:     people *p_map; 
      27:     char temp; 
      28:     if(argc < 2){
      29:         printf("usage %s filename\n",argv[0]);
      30:         exit(EXIT_FAILURE);
      31:     }
      32:     fd=open(argv[1],O_CREAT|O_RDWR|O_TRUNC,00777); 
      33:     if(fd == -1)
      34:     {
      35:         printf("error:%s\n",strerror(errno));
      36:      exit(EXIT_FAILURE);
      37:     }
      38:     lseek(fd,sizeof(people)*5-1,SEEK_SET); 
      39:     write(fd,"",1); 
      40:     p_map=(people*)mmap(NULL,sizeof(people)*10,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); 
      41:     close(fd); 
      42:     temp='a'; 
      43:     for(i=0;i<10;i++) 
      44:     { 
      45:          temp += 1; 
      46:      printf("%s\n",strerror(errno));
      47:          memcpy((*(p_map+i)).name,&temp,2); 
      48:          (*(p_map+i)).age=20+i; 
      49:     } 
      50:      printf("initialize over!\n"); 
      51:      sleep(10); 
      52:      munmap(p_map,sizeof(people)*10); 
      53:      printf("umap ok!\n"); 
      54:  } 
  • 相关阅读:
    12.13 Redis缓存面试题精简版
    12.12 Oracle数据库相关面试题精简版(后续继续完善)
    1.131 IDEA2018版本64位激活
    7.11 读《如何阅读一本书》有感
    Linux下source命令详解(转载)
    Scala 随笔
    SparkStreaming实时流式大数据处理实战总结
    转载:hive的一些udaf
    IDEA的一些常见报错
    hive使用UDF函数
  • 原文地址:https://www.cnblogs.com/justinzhang/p/2667200.html
Copyright © 2011-2022 走看看