|
| 1 | +#define _BSD_SOURCE |
| 2 | +#include <sys/mman.h> |
| 3 | +#include <sys/types.h> |
| 4 | +#include <fcntl.h> |
| 5 | +#include <stdio.h> |
| 6 | +#include <stdlib.h> |
| 7 | +#include <string.h> |
| 8 | +#include <unistd.h> |
| 9 | + |
| 10 | + |
| 11 | +// Try to emulate what we're doing in mmap with fwrite |
| 12 | +// This is a 3-file setup: |
| 13 | +// Start with a file full of 4096 X's |
| 14 | +// If you run this with no arguments, we just read the file and print it. |
| 15 | +// If you pass an argument, we take the first character and randomly write |
| 16 | +// that character to an offset in the file. |
| 17 | +#define MMAP_FILE_SIZE 4096 |
| 18 | + |
| 19 | +int main(int argc, char *argv[]) { |
| 20 | + const char *datafile = "data.in"; |
| 21 | + char printchar; |
| 22 | + int is_reader; |
| 23 | + char buf[MMAP_FILE_SIZE]; |
| 24 | + FILE *fp; |
| 25 | + off_t off; |
| 26 | + |
| 27 | + if (argc < 2) { |
| 28 | + // This is the reader process |
| 29 | + is_reader = 1; |
| 30 | + } else { |
| 31 | + is_reader = 0; |
| 32 | + printchar = argv[1][0]; |
| 33 | + } |
| 34 | + |
| 35 | + // We're going to open a file for mmapping and then we're going to |
| 36 | + // loop updating our character. |
| 37 | + fp = fopen(datafile, "r"); |
| 38 | + if (fp == NULL) { |
| 39 | + perror("open"); |
| 40 | + exit(1); |
| 41 | + } |
| 42 | + // Seed the random number generator so that different processes |
| 43 | + // will do different things. |
| 44 | + srandom((unsigned int)getpid()); |
| 45 | + while (1) { |
| 46 | + if (is_reader) { |
| 47 | + if (fseek(fp, 0, SEEK_SET) != 0 || |
| 48 | + fread(buf, MMAP_FILE_SIZE, 1, fp) != 1) { |
| 49 | + perror("fread"); |
| 50 | + exit(1); |
| 51 | + } |
| 52 | + for (int i = 0; i < MMAP_FILE_SIZE; i += 64) |
| 53 | + printf("%.64s\n", buf + i); |
| 54 | + sleep(1); |
| 55 | + } else { |
| 56 | + // Pick an offset and write it using stdio. |
| 57 | + off = random() % MMAP_FILE_SIZE; |
| 58 | + if (fseek(fp, off, SEEK_SET) != off || |
| 59 | + fwrite(&printchar, 1, 1, fp) != 1) { |
| 60 | + perror("writer failed\n"); |
| 61 | + exit(1); |
| 62 | + } |
| 63 | + usleep(1024); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + exit(0); |
| 68 | +} |
0 commit comments