Redirect stdin to a program to another process

I have a C program and I would like it to filter out all its data with tr. So, I would like to run tr as a child process, redirect my stdin to it, and then write tr stdout and read from it.

Edit: here is the code that I still have that doesn't work. This disappears instantly, but I don't understand why:

#include <stdlib.h> #include <stdio.h> int main(int argc, char** argv){ int ch; int fd = stripNewlines(); while((ch = getc(fd)) != EOF){ putc(ch, stdout); } return 0; } int stripNewlines(){ int fd[2], ch; pipe(fd); if(!fork()){ close(fd[0]); while((ch = getc(stdin)) != EOF){ if(ch == '\n'){ continue; } putc(ch, fd[1]); } exit(0); }else{ close(fd[1]); return fd[0]; } } 

Edit: It turns out that there were two things: one of them was that my header did not define stdin and stdout as 0 and 1, so I actually read / wrote completely random channels. Another thing is that for some reason getc and putc do not work as I expected, so I had to use read () and write (). If I do this, it will be perfect:

 #include <stdlib.h> #include <stdio.h> int main(int argc, char** argv){ int ch; int fd = stripNewlines(); while(read(fd, &ch, 1) == 1){ write(1, &ch, 1); } return 0; } int stripNewlines(){ int fd[2]; int ch; pipe(fd); if(!fork()){ close(fd[0]); while(read(0, &ch, 1) == 1){ if(ch == '\n'){ continue; } write(fd[1], &ch, 1); } exit(0); }else{ close(fd[1]); return fd[0]; } } 
+6
c unix stdin
source share
4 answers

Reading it from stdin makes life difficult. If you can live reading from another FILE * , it is fairly easy to use popen() to appear tr and read from FILE * it returns.

Edit: if you cannot do this, you need a little ugliness. Start by using popen to spawn tr with output redirection. Then use fileno to get the file numbers associated with this FILE * and with stdin . Finally, use dup2 to bind the stdin file descriptor to the pipe from tr .

+1
source share

See popen(3) . Basically all you have to do is

 FILE *in = popen("tr <args>", "r"); 

and then read from in .

+1
source share

Any reason why you simply cannot pass input from tr to your program?

tr AZ az | myprogram

0
source share
 #include <stdio.h> int main() { char x1[100]; scanf("%[^\n]",x1); // read entire line from tr ie, from stdin printf("\n%s",x1); } 

and use

tr AZ az | Myprogram

0
source share

All Articles