bash 管道输出到 bc 计算器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14171701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pipe output to bc calculator
提问by Xitac
Short version:
精简版:
I'm trying to get something like this to work in c using piping:
我正在尝试使用管道使这样的东西在 c 中工作:
echo 3+5 | bc
Longer version:
更长的版本:
Following simple instructions on pipes at http://beej.us/guide/bgipc/output/html/multipage/pipes.html, I tried creating something similar to last example on that page. To be precise, I tried to create piping in c using 2 processes. Child process to send his output to parent, and parent using that output for his calculations using bc calculator. I've basically copied the example on previously linked page, made a few simple adjustments to the code, but it's not working.
按照http://beej.us/guide/bgipc/output/html/multipage/pipes.html上有关管道的简单说明,我尝试创建类似于该页面上最后一个示例的内容。准确地说,我尝试使用 2 个进程在 c 中创建管道。子进程将他的输出发送给父进程,父进程使用该输出使用 bc 计算器进行计算。我基本上复制了之前链接页面上的示例,对代码进行了一些简单的调整,但它不起作用。
Here is my code:
这是我的代码:
#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;
}
I'm getting (standard_in) 1: syntax error message when running that. I also tried using read/write but result is the same.
我在运行时收到 (standard_in) 1: 语法错误消息。我也尝试使用读/写,但结果是一样的。
What am I doing wrong? Thank you!
我究竟做错了什么?谢谢!
采纳答案by Jens
You must end the input for bcwith a newline. Use
您必须bc以换行符结束输入。用
printf("3+3\n");
and it'll magically work! BTW, you can verify that this is the problem with
它会神奇地起作用!顺便说一句,您可以验证这是问题所在
$ printf '3+3' | bc
bc: stdin:1: syntax error: unexpected EOF
$ printf '3+3\n' | bc
6

