【问题标题】:Pipe output to bc calculator管道输出到 bc 计算器
【发布时间】:2012-12-19 18:01:23
【问题描述】:

短版:

我正在尝试使用管道让这样的东西在 c 中工作:

echo 3+5 | bc

加长版:

按照http://beej.us/guide/bgipc/output/html/multipage/pipes.html 上有关管道的简单说明,我尝试创建类似于该页面上最后一个示例的内容。准确地说,我尝试使用 2 个进程在 c 中创建管道。子进程将其输出发送给父进程,父进程使用该输出进行计算,使用 bc 计算器。我基本上复制了之前链接页面上的示例,对代码进行了一些简单的调整,但它不起作用。

这是我的代码:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(void)
{
    int pfds[2];
    pipe(pfds);

    if (!fork()) {
        close(1);       /* close normal stdout */
        dup(pfds[1]);   /* make stdout same as pfds[1] */
        close(pfds[0]); /* we don't need this */
        printf("3+3");
        exit(0);
    } else {
        close(0);       /* close normal stdin */
        dup(pfds[0]);   /* make stdin same as pfds[0] */
        close(pfds[1]); /* we don't need this */
        execlp("bc", "bc", NULL);
    }
    return 0;
}

我得到 (standard_in) 1: 运行时的语法错误消息。我也尝试过使用读/写,但结果是一样的。

我做错了什么?谢谢!

【问题讨论】:

  • 让我印象深刻的一件事是,您在这里可能有种族危险。
  • @OliCharlesworth 您认为比赛的潜力在哪里? child 中的 write() 和 bc 的 read() 由内核 IIUC 同步。

标签: c bash pipe bc


【解决方案1】:

您必须以换行符结束 bc 的输入。使用

printf("3+3\n");

它会神奇地工作!顺便说一句,您可以验证这是问题所在

$ printf '3+3' | bc
bc: stdin:1: syntax error: unexpected EOF
$ printf '3+3\n' | bc
6

【讨论】:

  • 我确定你会这么说:-)
猜你喜欢
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 2019-02-16
  • 2014-11-07
  • 1970-01-01
相关资源
最近更新 更多