Debian Codegraph @

listings/chapter-5/mmap-read.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <fcntl.h>
10 #include <sys/mman.h>
11 #include <sys/stat.h>
12 #include <unistd.h>
13 #define FILE_LENGTH 0x100
14
15 int main (int argc, char* const argv[])
16 {
17 int fd;
18 void* file_memory;
19 int integer;
20
21 /* Open the file. */
22 fd = open (argv[1], O_RDWR, S_IRUSR | S_IWUSR);
23 /* Create the memory-mapping. */
24 file_memory = mmap (0, FILE_LENGTH, PROT_READ | PROT_WRITE,
25 MAP_SHARED, fd, 0);
26 close (fd);
27
28 /* Read the integer, print it out, and double it. */
29 sscanf (file_memory, "%d", &integer);
30 printf ("value: %d\n", integer);
31 sprintf ((char*) file_memory, "%d\n", 2 * integer);
32 /* Release the memory (unnecessary since the program exits). */
33 munmap (file_memory, FILE_LENGTH);
34
35 return 0;
36 }