size_t size = 4096;
int fd;
int len, nwrite;
- struct stat sb;
+ struct stat fdata;
/*
* Input section: decode command line parameters
* Use getopt function
*/
opterr = 0; /* don't want writing to stderr */
- while ( (i = getopt(argc, argv, "h")) != -1) {
+ while ( (i = getopt(argc, argv, "hs:")) != -1) {
switch (i) {
/*
* Handling options
usage();
return -1;
break;
- case 's': /* take wait time for childen */
+ case 's': /* buffer size */
size = strtol(optarg, NULL, 10); /* convert input */
break;
case '?': /* unrecognized options */
/*
* 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);
+ len = tee(STDIN_FILENO, STDOUT_FILENO, size, 0);
+ fprintf(stderr, "Copied %d byte\n", len); /* debug (use stderr!) */
+ if (len == 0) break;
if (len < 0) {
if (errno == EAGAIN) {
continue;
perror("error on tee stdin to stdout");
exit(EXIT_FAILURE);
}
- } else {
- if (len == 0) break;
- }
- fprintf(stderr, "Copied %d byte\n", len);
+ }
/* write data to the file using splice */
while (len > 0) {
nwrite = splice(STDIN_FILENO, NULL, fd, NULL, len, SPLICE_F_MOVE);
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);