Finito con {{{tee}}}, spostati un po' di TODO, messo il placeholder
[gapil.git] / sources / tee.c
index 18f01a2a3a6dc053ed895a80daa2636fe9bd0ac6..559c94987cf010ed516e64cf280a96abbab8c731 100644 (file)
@@ -56,7 +56,7 @@ int main(int argc, char *argv[])
     size_t size = 4096;
     int fd;
     int len, nwrite;
-    struct stat sb;
+    struct stat fdata;
     /*
      * Input section: decode command line parameters 
      * Use getopt function
@@ -85,41 +85,38 @@ int main(int argc, char *argv[])
    /*
     * Main body
     */
-    if ((argc - optind) != 1) { /* There must two argument */
+    if ((argc - optind) != 1) { /* There must be one argument */
         printf("Wrong number of arguments %d\n", argc - optind);
         usage();
     }
-    /* open destination file */
+    /* open destination file and check stdin and stdout */
     fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0644);
     if (fd == -1) {
         printf("cannot open destination file %s, %s", argv[1], 
               strerror(errno));
         exit(EXIT_FAILURE);
     }
-
-
-    if (fstat(STDIN_FILENO, &sb) < 0) {
+    if (fstat(STDIN_FILENO, &fdata) < 0) {
        perror("stat");
        exit(EXIT_FAILURE);
     }
-    if (!S_ISFIFO(sb.st_mode)) {
+    if (!S_ISFIFO(fdata.st_mode)) {
        fprintf(stderr, "stdin must be a pipe\n");
        exit(EXIT_FAILURE);
     }
-    if (fstat(STDOUT_FILENO, &sb) < 0) {
+    if (fstat(STDOUT_FILENO, &fdata) < 0) {
        perror("stat");
        exit(EXIT_FAILURE);
     }
-    if (!S_ISFIFO(sb.st_mode)) {
+    if (!S_ISFIFO(fdata.st_mode)) {
        fprintf(stderr, "stdout must be a pipe\n");
        exit(EXIT_FAILURE);
     }
-
     /* tee loop */
-    //debug("Size %d\n", size);
     while (1) {
         /* copy stdin to stdout */
         len = tee(STDIN_FILENO, STDOUT_FILENO, size, SPLICE_F_NONBLOCK);
+       if (len == 0) break;
         if (len < 0) {
             if (errno == EAGAIN) {
                continue;
@@ -127,10 +124,8 @@ int main(int argc, char *argv[])
                perror("error on tee stdin to stdout");
                exit(EXIT_FAILURE);
            }
-        } else {
-            if (len == 0) break;
-       }
-       fprintf(stderr, "Copied %d byte\n", len);
+        }
+       fprintf(stderr, "Copied %d byte\n", len); /* debug (use stderr!) */
         /* write data to the file using splice */
         while (len > 0) {
             nwrite = splice(STDIN_FILENO, NULL, fd, NULL, len, SPLICE_F_MOVE);
@@ -151,7 +146,7 @@ int main(int argc, char *argv[])
 void usage(void) {
     printf("Program tee: duplicate stdin to stdout and a file\n");
     printf("Usage:\n");
-    printf("  splicecp [-h] [-s N] filename\n");
+    printf("  tee [-h] [-s N] filename\n");
     printf("  -h           print this help\n");
     printf("  -s N         set a buffer size of N bytes \n");
     exit(1);