Programma di prova per l'uso di {{{tee}}}
[gapil.git] / sources / tee.c
1 #define _GNU_SOURCE
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <assert.h>
7 #include <errno.h>
8 #include <limits.h>
9
10
11 int main(int argc, char *argv[])
12 {
13    /*
14     * Variables definition
15     */
16     int i;
17     int size = 4096;
18     int fd;
19     int len, nwrite;
20     /*
21      * Input section: decode command line parameters 
22      * Use getopt function
23      */
24     opterr = 0;  /* don't want writing to stderr */
25     while ( (i = getopt(argc, argv, "h")) != -1) {
26         switch (i) {
27         /* 
28          * Handling options 
29          */ 
30         case 'h':      /* help option */
31             printf("Wrong -h option use\n");
32             usage();
33             return -1;
34             break;
35         case 's':      /* take wait time for childen */
36             size = strtol(optarg, NULL, 10);    /* convert input */
37             break;
38         case '?':      /* unrecognized options */
39             printf("Unrecognized options -%c\n", optopt);
40             usage();
41         default:       /* should not reached */
42             usage();
43         }
44     }
45    /*
46     * Main body
47     */
48     if ((argc - optind) != 1) { /* There must two argument */
49         printf("Wrong number of arguments %d\n", argc - optind);
50         usage();
51     }
52     /* open destination file */
53     fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0644);
54     if (fd == -1) {
55         printf("cannot open destination file %s, %s", argv[1], 
56                strerror(errno));
57         exit(EXIT_FAILURE);
58     }
59     /* tee loop */
60     while (1) {
61         /* copy stdin to stdout */
62         len = tee(STDIN_FILENO, STDOUT_FILENO, size, SPLICE_F_NONBLOCK);
63         if (len < 0) {
64             if (errno == EAGAIN) {
65                 continue;
66             } else {
67                 perror("error on tee stdin to stdout");
68                 exit(EXIT_FAILURE);
69             }
70         } else {
71             if (len == 0) break;
72         }
73         /* write data to the file using splice */
74         while (len > 0) {
75             nwrite = splice(STDIN_FILENO, NULL, fd, NULL, len, SPLICE_F_MOVE);
76             if (nwrite < 0) {
77                 perror("error on splice stdin to file");
78                 break;
79             }
80             len -= nwrite;
81         }
82     }
83     close(fd);
84     exit(EXIT_SUCCESS);
85 }