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]; } }
c unix stdin
Ross Andrews
source share