【发布时间】:2010-04-21 03:47:40
【问题描述】:
我有一个 C 程序,我想让它用 tr 过滤所有输入。所以,我想将 tr 作为子进程启动,将我的标准输入重定向到它,然后捕获 tr 的标准输出并从中读取。
编辑:这是我到目前为止的代码,它不起作用。它立即出现段错误,但我不明白为什么:
#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];
}
}
编辑:原来这是两件事:一是我的标头没有将标准输入和标准输出定义为 0 和 1,所以我实际上是在读/写完全随机的管道。另一个是由于某种原因 getc 和 putc 不能按我的预期工作,所以我不得不使用 read() 和 write() 代替。如果我这样做,那就完美了:
#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];
}
}
【问题讨论】: