我有一个C程序,我想让它用tr过滤所有输入.所以,我想启动tr作为子进程,将我的stdin重定向到它,然后捕获tr的stdout并从中读取.
编辑:这是我到目前为止的代码,它不起作用.它立即发生了段错误,但我不明白为什么:
#include
#include
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];
}
}
编辑:原来这是两件事:一个是我的标题没有将stdin和stdout定义为0和1,所以我实际上正在读/写完全随机的管道.另一个原因是由于某种原因,getc和putc不能正常工作,所以我不得不使用read()和write().如果我这样做,它是完美的:
#include
#include
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];
}
}