#include <stdio.h>
#define BASE 0
-#define SIZE 10
#ifndef MAP_FAILED
#define MAP_FAILED ((void *)-1)
-#endif
+#endif /* not MAP_FAILED */
void usage(void)
{
caddr_t pa;
int rw_flag = -1; /* 0=read, 1=read+write */
char *filename, byte;
+ int i, size;
+ struct stat buf;
/* check input args */
if (argc != 3)
filename = argv[2];
+ /* find size of file */
+ if (stat(filename, &buf) < 0) {
+ perror("stat");
+ exit(1);
+ }
+ size = buf.st_size;
+
/* open input file */
if (rw_flag)
fd = open(filename, O_RDWR);
/* mmap the input file */
pa = mmap((caddr_t) 0,
- SIZE,
+ size,
(rw_flag ? (PROT_READ | PROT_WRITE) : PROT_READ),
MAP_SHARED,
fd,
}
printf("file is mapped with address %p\n", pa);
- /* now read the first byte of that file */
- byte = pa[0];
- printf("byte 0 is decimal %03d (\'%c\')\n",
- byte, isprint(byte) ? byte : '.');
+ /* now read every 1024-th byte */
+ for (i=0; i<size; i+=1024) {
+ byte = pa[i];
+ printf("byte 0 is decimal %03d (\'%c\')\n",
+ byte, isprint(byte) ? byte : '.');
+ }
/* for a read-write test, modify the first byte */
if (rw_flag)
pa[0] += 1;
- /* msync the file */
- if (msync(pa, SIZE, MS_SYNC) < 0) {
- perror("msync");
- exit(1);
- }
+
+ /* msync the file, but only if we're modifying the file */
+ if (rw_flag)
+ if (msync(pa, size, MS_SYNC) < 0) {
+ perror("msync");
+ exit(1);
+ }
printf("file is msynchronized\n");
/* unmap the file */
- if (munmap(pa, SIZE) < 0) {
+ if (munmap(pa, size) < 0) {
perror("munmap");
exit(1);
}
/* re-mmap the input file */
pa = mmap((caddr_t) 0,
- SIZE,
+ size,
PROT_READ,
MAP_SHARED,
fd,
exit(1);
}
/* unmap the file */
- if (munmap(pa, SIZE) < 0) {
+ if (munmap(pa, size) < 0) {
perror("munmap");
exit(1);
}