File: funnel.cpp

package info (click to toggle)
logtools 0.13g
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 316 kB
  • sloc: cpp: 1,110; sh: 116; makefile: 46
file content (101 lines) | stat: -rw-r--r-- 1,687 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#include "logtools.h"

void usage()
{
  fprintf(stderr, "Usage: funnel [|] [>[>]file] [|program]\n"
  "\nVersion: " VERSION "\n");
  exit(ERR_PARAM);
}

PFILE openit(const char *arg)
{
  const char *ptr = arg;
  PFILE ret = NULL;

  if(!strcmp(arg, "|"))
    return stdout;

  if(ptr[0] == '>')
  {
    const char *mode = "w";
    ptr++;
    if(ptr[0] == '>')
    {
      ptr++;
      mode = "a";
    }
    ret = fopen(ptr, mode);
  }
  else if(ptr[0] == '|')
  {
    ptr++;
    ret = popen(ptr, "w");
  }
  else
  {
    fprintf(stderr, "Bad command \"%s\".\n", arg);
    return NULL;
  }
  return ret;
}

int main(int argc, char **argv)
{
  if(argc < 2)
    usage();

  PFILE *out = new PFILE[argc];

  int i;
  for(i = 1; i < argc; i++)
  {
    out[i] = openit(argv[i]);
  }
  char buf[8192];
  size_t rc;
  int count = argc - 1;
  int errors = 0;
  int f = fcntl(0, F_GETFL);
  if(f == -1 || -1 == fcntl(0, F_SETFL, f & (!O_NONBLOCK)) )
  {
    fprintf(stderr, "Can't fcntl\n");
    return ERR_INPUT;
  }

  while( int(rc = read(0, buf, sizeof(buf)) ) > 0 && count > 0)
  {
    if(rc)
    {
      for(i = 1; i < argc; i++)
      {
        if(out[i])
        {
          size_t wrote = fwrite(buf, rc, 1, out[i]);
          if(wrote != 1)
          {
            fclose(out[i]);
            out[i] = NULL;
            fprintf(stderr, "Output \"%s\" aborted.\n", argv[i]);
            count--;
            errors++;
          }
        }
      }
      fflush(NULL);
    }
  }
  close(0);
  for(i = 1; i < argc; i++)
  {
    if(out[i])
      fclose(out[i]);
  }
  return 100 + errors;
}