Trattate anche {{{vmslice}}} e {{{tee}}}, e scritto esempio di
[gapil.git] / listati / splicecp.c
1 #define _GNU_SOURCE
2 #include <fcntl.h>       /* file control functions */
3 ...
4
5 int main(int argc, char *argv[])
6 {
7     int size = 4096;
8     int pipefd[2];
9     int in_fd, out_fd;
10     int nread, nwrite;
11     ...
12    /* Main body */
13     if ((argc - optind) != 2) { /* There must two argument */
14         printf("Wrong number of arguments %d\n", argc - optind);
15         usage();
16     }
17     /* open pipe, input and output file */
18     in_fd = open(argv[optind], O_RDONLY);
19     if (in_fd < 0) {
20         printf("Input error %s on %s\n", strerror(errno), argv[optind]);
21         exit(EXIT_FAILURE); 
22     }
23     out_fd = open(argv[optind+1], O_CREAT|O_RDWR|O_TRUNC, 0644);
24     if (out_fd < 0) {
25         printf("Cannot open %s, error %s\n", argv[optind+1], strerror(errno));
26         exit(EXIT_FAILURE); 
27     }
28     if (pipe(pipefd) == -1) {
29         perror("Cannot create buffer pipe"); 
30         exit(EXIT_FAILURE); 
31     }
32     /* copy loop */
33     while (1) {
34         nread = splice(in_fd, NULL, pipefd[1], NULL, size, 
35                        SPLICE_F_MOVE|SPLICE_F_MORE);
36         if (nread == 0) break;
37         if (nread < 0) {
38             if (errno == EINTR) {
39                 continue;
40             } else {
41                 perror("read error");
42                 exit(EXIT_FAILURE);
43             } 
44         }
45         while (nread > 0) {
46             nwrite = splice(pipefd[0], NULL, out_fd, NULL, nread, 
47                             SPLICE_F_MOVE|SPLICE_F_MORE);
48             if (nwrite < 0) {
49                 if (errno == EINTR)
50                     continue;
51                 else {
52                     perror("write error");
53                     exit(EXIT_FAILURE);
54                 }
55             }
56             nread -= nwrite;
57         }
58     }
59     return EXIT_SUCCESS;
60 }