Introduce old redir program
[lcapit-junk-code.git] / books / apue / mmap.c
blob2fe4225bda5d6c57aa46f3b8e6124d7824e67c53
1 /*
2 * cp example using mmap()
3 */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <fcntl.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <sys/mman.h>
13 int main(int argc, char *argv[])
15 char *src, *dst;
16 int err, fdin, fdout;
17 struct stat statbuf;
19 if (argc != 3) {
20 fprintf(stderr, "usage: 12.14 <fromfile> <tofile>\n");
21 exit(EXIT_FAILURE);
24 fdin = open(argv[1], O_RDONLY);
25 if (fdin < 0) {
26 fprintf(stderr, "can't open %s for reading", argv[1]);
27 exit(EXIT_FAILURE);
30 fdout = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0666);
31 if (fdin < 0) {
32 fprintf(stderr, "can't open %s for reading", argv[2]);
33 exit(EXIT_FAILURE);
36 err = fstat(fdin, &statbuf);
37 if (err) {
38 perror("fstat()");
39 exit(EXIT_FAILURE);
42 /* Allocates the space needed */
43 err = lseek(fdout, statbuf.st_size -1, SEEK_SET);
44 if (err == (off_t) -1) {
45 perror("lseek()");
46 exit(EXIT_FAILURE);
49 err = write(fdout, "", 1);
50 if (err != 1) {
51 perror("write()");
52 exit(EXIT_FAILURE);
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()");
59 exit(EXIT_FAILURE);
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()");
66 exit(EXIT_FAILURE);
69 memcpy(dst, src, statbuf.st_size);
71 munmap(src, statbuf.st_size);
72 munmap(dst, statbuf.st_size);
74 return 0;