00001 #include <fcntl.h>
00002 #include <string.h>
00003 #include <errno.h>
00004 #include <signal.h>
00005
00006 #include "bchash.h"
00007 #include "file.h"
00008 #include "guicast.h"
00009 #include "interlacemodes.h"
00010 #include "pipe.h"
00011
00012 extern "C"
00013 {
00014 int pipe_sigpipe_received;
00015
00016 void pipe_handle_sigpipe(int signum)
00017 {
00018 printf("Received sigpipe\n");
00019 pipe_sigpipe_received++;
00020 }
00021 }
00022
00023 Pipe::Pipe(char *command, char *sub_str, char sub_char)
00024 {
00025 this->command = command;
00026 this->sub_str = sub_str;
00027 this->sub_char = sub_char;
00028
00029 complete[0] = '\0';
00030 file = NULL;
00031 fd = -1;
00032
00033
00034 signal(SIGPIPE, pipe_handle_sigpipe);
00035 }
00036
00037 Pipe::~Pipe()
00038 {
00039 close();
00040 }
00041
00042 int Pipe::substitute()
00043 {
00044 if (command == NULL)
00045 {
00046 strcpy(complete, "");
00047 return 0;
00048 }
00049
00050 if (sub_str == NULL || sub_char == '\0')
00051 {
00052 strcpy(complete, command);
00053 return 0;
00054 }
00055
00056 int count = 0;
00057 char *c = command;
00058 char *f = complete;
00059 while (*c)
00060 {
00061
00062 if (*c != sub_char)
00063 {
00064 *f++ = *c++;
00065 continue;
00066 }
00067
00068
00069 c++;
00070
00071
00072 if (*c == sub_char) {
00073 *f++ = *c++;
00074 continue;
00075 }
00076
00077
00078 if (f + strlen(sub_str) - complete > sizeof(complete))
00079 {
00080 printf("Pipe::substitute(): max length exceeded\n");
00081 return -1;
00082 }
00083 strcpy(f, sub_str);
00084 f += strlen(sub_str);
00085 count++;
00086 }
00087
00088 return count;
00089 }
00090
00091
00092
00093 int Pipe::open(char *mode)
00094 {
00095 if (file) close();
00096
00097 if (mode == NULL)
00098 {
00099 printf("Pipe::open(): no mode given\n");
00100 return 1;
00101 }
00102
00103 if (substitute() < 0)
00104 return 1;
00105
00106 if (complete == NULL || strlen(complete) == 0)
00107 {
00108 printf("Pipe::open(): no pipe to open\n");
00109 return 1;
00110 }
00111
00112 printf("trying popen(%s)\n", complete);
00113 file = popen(complete, mode);
00114 if (file != NULL)
00115 {
00116 fd = fileno(file);
00117 return 0;
00118 }
00119
00120
00121
00122
00123 printf("Pipe::open(%s,%s) failed: %s\n",
00124 complete, mode, strerror(errno));
00125 return 1;
00126 }
00127
00128 int Pipe::open_read()
00129 {
00130 return open("r");
00131 }
00132
00133 int Pipe::open_write()
00134 {
00135 return open("w");
00136 }
00137
00138 void Pipe::close()
00139 {
00140 pclose(file);
00141 file = 0;
00142 fd = -1;
00143 }