我有一個C程序,我想讓它用tr來過濾它的所有輸入。所以,我想將tr作爲子進程啓動,將stdin重定向到它,然後捕獲tr的stdout並從中讀取。將C程序中的stdin重定向到另一個進程
編輯:這是我到目前爲止的代碼,這是行不通的。它出現segfaults瞬間,但我不明白爲什麼:
#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];
}
}
編輯:原來這是兩兩件事:一個是,我的頭沒有界定標準輸入和stdout爲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];
}
}
是的,但它進行得有點複雜。我想在程序內部處理所有這些。 – 2010-04-21 03:50:59