2 * cp example using mmap()
13 int main(int argc
, char *argv
[])
20 fprintf(stderr
, "usage: 12.14 <fromfile> <tofile>\n");
24 fdin
= open(argv
[1], O_RDONLY
);
26 fprintf(stderr
, "can't open %s for reading", argv
[1]);
30 fdout
= open(argv
[2], O_RDWR
| O_CREAT
| O_TRUNC
, 0666);
32 fprintf(stderr
, "can't open %s for reading", argv
[2]);
36 err
= fstat(fdin
, &statbuf
);
42 /* Allocates the space needed */
43 err
= lseek(fdout
, statbuf
.st_size
-1, SEEK_SET
);
44 if (err
== (off_t
) -1) {
49 err
= write(fdout
, "", 1);
55 src
= (char *) mmap((void *) 0, statbuf
.st_size
,
56 PROT_READ
, MAP_SHARED
, fdin
, 0);
57 if (src
== MAP_FAILED
) {
58 perror("first mmap()");
62 dst
= (char *) mmap((void *) 0, statbuf
.st_size
,
63 PROT_READ
| PROT_WRITE
, MAP_SHARED
, fdout
, 0);
64 if (dst
== MAP_FAILED
) {
65 perror("second mmap()");
69 memcpy(dst
, src
, statbuf
.st_size
);
71 munmap(src
, statbuf
.st_size
);
72 munmap(dst
, statbuf
.st_size
);