【发布时间】: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 同步。