【问题标题】:Why my pipe ends only when i send a SIGINT为什么我的管道只有在我发送 SIGINT 时才结束
【发布时间】:2017-01-26 11:51:46
【问题描述】:

基本上,我正在用 C 编写一个 shell。 我正在尝试实现管道功能,这几乎完成了:

 > ls | cat -e | wc | wc -l
 > 1

但我在尝试管道更慢/更长的执行时遇到问题。

确实,当我尝试通过管道传输 'cat /dev/urandom' 的结果时,它基本上是在等待...

> cat /dev/urandom | cat
>

但是,当我发送一个 SIGINT(使用 ctrl + c)来停止它时,它会在 STDOUT 上打印结果缓冲区..

when i ctrl + c , cat /dev/urandom

所以我的问题是:我应该去哪里尝试解决这个问题?

我的管道执行部分:

    int         exec_apipe(t_me *me, t_node *curs, int is_last)
{
    int     pfd[2];
    int     pid;

    if (pipe(pfd) == -1 || !curs)
        return (0);
    if (!(curs->pid = fork()))
    {
        dup2(me->fd_in, 0);
        me->fd_in > 0 ? close(me->fd_in) : 0;
        if (!is_last)
            dup2(pfd[1], 1);
        else if (curs->parent->parent && curs->parent->parent->fd_out >= 0)
            dup2(curs->parent->parent->fd_out, 1);
        close(pfd[0]);
        exec_mpipe(me, curs);
        exit(-1);
    }
    else if (curs->pid > 0)
    {
        waitpid(curs->pid, &(curs->ret), WUNTRACED);
        handle_pid(me, curs->ret);
        close(pfd[1]);
        me->fd_in = pfd[0];
    }
    return (pid >= 0 ? 1 : -1);
}

我希望有人能理解我在说什么,也许可以帮助.. 谢谢

【问题讨论】:

标签: c shell pipe zsh waitpid


【解决方案1】:

您需要启动管道中的所有程序,然后等待任何程序完成。

您的 shell 实现正在等待每个管道元素完成,然后再开始下一个。但是/dev/urandom是源源不断的; cat /dev/urandom 将一直运行直到被杀死。所以第二个cat 永远不会开始,直到你控制-C 第一个。

【讨论】:

  • 感谢您非常准确和明确的回答,这很容易解决!再次感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
相关资源
最近更新 更多