将输出导入到bc计算器

8

简短版:

我正在尝试使用管道在c中实现类似这样的功能:

echo 3+5 | bc

更长的版本:

按照http://beej.us/guide/bgipc/output/html/multipage/pipes.html上的简单指南,我尝试创建类似该页面上最后一个示例的内容。确切地说,我尝试使用两个进程在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:语法错误”消息。我也尝试使用读/写,但结果相同。

我做错了什么?谢谢!


有一件事让我想到了,你可能在这里存在竞争危害。 - Oliver Charlesworth
@OliCharlesworth,你觉得哪里有竞争的潜力?如果我没理解错的话,子进程中的write()和bc的read()是由内核同步的。 - Jens
1个回答

7

您必须在使用bc命令时以换行符结束输入。请使用

printf("3+3\n");

然后它就会神奇地工作!顺便说一下,你可以通过

验证这是否是问题。
$ printf '3+3' | bc
bc: stdin:1: syntax error: unexpected EOF
$ printf '3+3\n' | bc
6

我确定你会这么说 :-) - Jens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接