管道输出到bc计算器

时间:2013-01-05 12:19:41

标签: c bash pipe bc

简短版:

我正在尝试使用管道来实现这样的工作:

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:语法错误消息。我也尝试过使用读/写但结果是一样的。

我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:6)

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

printf("3+3\n");

它会神奇地工作!顺便说一句,你可以验证这是

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