2016-11-11 3 views
0

私は、コンソール入力(私がUNIXで入力したもの)から単語を数えるために子プロセスを使用しようとしています。ここに私のコードは次のとおりです。子プロセスを使用して入力を読み取っていますか?

int main(){ 
    int pipe1[2]; 
    int child_value; 

    pipe(pipe1); 
    child_value= fork(); 

    if(child_value > 0){ 
    /*parent*/ 
    int word_count; 
    dup2(STDIN_FILENO, pipe1[0]); 

    close(pipe1[0]); 

    scanf("%d", &word_count); 
    printf("%d\n", word_count); 
    } else if (child_value == 0) { 
    /*child*/ 
    dup2(pipe1[1], STDOUT_FILENO); 
    close(pipe1[1]); 
    execl("/usr/bin/wc", "wc", "-w", NULL); 
    err(EX_OSERR, "exec error"); 

    } else err(EX_OSERR, "fork error"); 

    return 0; 
} 

私のコンソール上に表示される出力は、私がコンソールに入力する内容無視して常に0である、と私は常にエラーが言ってます:

wc: standard input: Input/output error 
+0

あなたが使用している場合パイプの一端を標準入力または標準出力にマップするには、 'dup2()'または 'dup()'を使用すると、後でパイプの両端を閉じることはほぼ確実です。例外は非常に少なく、遠いです。パイプの両端を閉じないようにする必要があるときは、わかります。しかし、それはあなたの問題の直接の原因ではありません。 –

+0

「dup2(STDIN_FILENO、pipe1 [0]);」と「dup2(pipe1 [1]、STDOUT_FILENO);」です。 2つ目の引数として、標準ファイル番号を両方指定する必要があります。 –

+0

dup2(pipe1 [1]、STDOUT_FILENO)とdup2(pipe1 [0]、STDIN_FILENO)である必要がありますか? –

答えて

1

コメントで述べたように:

dup2()またはdup()を使用してパイプの一端を標準入力または標準出力にマップすると、後でパイプの両端を閉じることがほぼ確実です。例外は非常に少なく、遠いです。パイプの両端を閉じないようにする必要があるときは、わかります。しかし、それはあなたの問題の直接の原因ではありません。

比較:dup2(STDIN_FILENO, pipe1[0]);dup2(pipe1[1], STDOUT_FILENO);。 2つ目の引数として、標準ファイル番号を両方指定する必要があります。

#include <err.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <sysexits.h> 
#include <unistd.h> 

int main(void) 
{ 
    int pipe1[2]; 
    int child_value; 

    pipe(pipe1); 
    child_value = fork(); 

    if (child_value > 0) 
    { 
     /*parent*/ 
     int word_count; 
     dup2(pipe1[0], STDIN_FILENO); 

     close(pipe1[0]); 
     close(pipe1[1]); 

     scanf("%d", &word_count); 
     printf("%d\n", word_count); 
    } 
    else if (child_value == 0) 
    { 
     /*child*/ 
     dup2(pipe1[1], STDOUT_FILENO); 
     close(pipe1[1]); 
     close(pipe1[0]); 
     execl("/usr/bin/wc", "wc", "-w", NULL); 
     err(EX_OSERR, "exec error"); 
    } 
    else 
     err(EX_OSERR, "fork error"); 

    return 0; 
} 

出力例(プログラムxx19):

$ ./xx19 
So she went into the garden 
to cut a cabbage-leaf 
to make an apple-pie 
and at the same time 
a great she-bear coming down the street 
pops its head into the shop 
What no soap 
So he died 
and she very imprudently married the Barber 
and there were present 
the Picninnies 
and the Joblillies 
and the Garyulies 
and the great Panjandrum himself 
with the little round button at top 
and they all fell to playing the game of catch-as-catch-can 
till the gunpowder ran out at the heels of their boots 
90 
$ 

(。あなたはそのナンセンス散文はどこから来るのかを見つけるために 'パンジャンドラム' をGoogleで検索することができます)

関連する問題