使用子进程读取输入?

时间:2016-11-11 14:49:15

标签: c process pipe fork

我试图使用子进程来计算控制台输入中的单词(我在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

1 个答案:

答案 0 :(得分:1)

如评论中所述:

  

当您使用dup2()或dup()将管道的一端映射到标准输入或标准输出时,之后关闭管道的两端几乎总是正确的。例外情况很少而且很远;你会知道什么时候需要避免关闭管道的两端。但是,这不是问题的直接原因。

     

比较:dup2(STDIN_FILENO, pipe1[0]);dup2(pipe1[1], STDOUT_FILENO);。他们都应该将标准文件号列为第二个参数。

#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上搜索“Panjandrum”以查找废话散文的来源。)