2010-04-21 52 views
6

我有一個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]; 
    } 
} 

回答

0

你爲什麼不能將輸入從tr傳遞到你的程序?

tr A-Z a-z | myprogram

+0

是的,但它進行得有點複雜。我想在程序內部處理所有這些。 – 2010-04-21 03:50:59

1

stdin讀它使生活更加困難。如果你可以繼續讀FILE *,那麼使用popen()來產卵tr並且從FILE *讀取它很容易。

編輯:如果你不能這樣做,那麼你需要進入一點醜陋。首先使用popen產生tr,其輸出重定向。然後使用fileno獲取與該FILE *stdin相關聯的文件編號。最後,使用dup2stdin的文件描述符與來自tr的管道相關聯。

+1

是的,這讓我不得不提問這個問題。如果我能做到這一點,我會的。 :-) – 2010-04-21 04:01:08

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

,並使用

TR A-Z A-Z | myprogram

1

請參閱popen(3)。基本上所有你需要做的是

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

然後從in讀。

相關問題