Debian Codegraph @

listings/chapter-5/mmap-write.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 <time.h>
13 #include <unistd.h>
14 #define FILE_LENGTH 0x100
15
16 /* Return a uniformly random number in the range [low,high]. */
17
18 int random_range (unsigned const low, unsigned const high)
19 {
20 unsigned const range = high - low + 1;
21 return low + (int) (((double) range) * rand () / (RAND_MAX + 1.0));
22 }
23
24 int main (int argc, char* const argv[])
25 {
26 int fd;
27 void* file_memory;
28
29 /* Seed the random number generator. */
30 srand (time (NULL));
31
32 /* Prepare a file large enough to hold an unsigned integer. */
33 fd = open (argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
34 lseek (fd, FILE_LENGTH+1, SEEK_SET);
35 write (fd, "", 1);
36 lseek (fd, 0, SEEK_SET);
37
38 /* Create the memory-mapping. */
39 file_memory = mmap (0, FILE_LENGTH, PROT_WRITE, MAP_SHARED, fd, 0);
40 close (fd);
41 /* Write a random integer to memory-mapped area. */
42 sprintf((char*) file_memory, "%d\n", random_range (-100, 100));
43 /* Release the memory (unnecessary since the program exits). */
44 munmap (file_memory, FILE_LENGTH);
45
46 return 0;
47 }