mmap() HOWTO

| No Comments | No TrackBacks

デバイスドライバ書いてると、mmap() が使えるようにしたいなー、とか思うわけで。

みたいな記事を読んで、理解できた気がするね。「Linux デバイスドライバ」という本がすごいわけですが、あれだけだとちょっと不十分な感じだったのだ。

そういえば普通にファイルを mmap() して読み書き、というのもやったことないや、と思ったので、ちょっと書いてみた。

#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>

int main(){
  int fd;
  char* p;
  int i;

  fd = open("textfile", O_RDWR);
  if(fd<0) printf("can't open!\n");
  printf("fd=%d\n", fd);
  p= (char*)mmap(NULL, 100, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, 0);
  printf("p=%lx\n", (long unsigned int)p);
  if(p==MAP_FAILED) printf("can't mmap!\n");

  for(i=0; i<100; i++)
    putchar(p[i]);

  for(i=0; i<10; i++)
    p[i]=0x30+i;

  close(fd);
  return 0;
}

これで、配列の値を変更した通りにちゃんとファイルが書き換わる。Unix はかっこいい仕掛けがいっぱいあるなー。

No TrackBacks

TrackBack URL: http://yasu2.prosou.nu/mt/mt-tb.cgi/2145

Leave a comment

OpenID accepted here Learn more about OpenID
Powered by Movable Type 5.02

September 2010

Sun Mon Tue Wed Thu Fri Sat
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    

About this Entry

This page contains a single entry by Yasunori Osana published on January 24, 2010 11:18 PM.

EOS-RT: Roll 1 was the previous entry in this blog.

きょうのじてんしゃ is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.