1
我想让两个进程通过Linux上的两个命名管道相互通信。 每个进程都是一个Unix过滤器:它读取标准输入上的数据并在其标准输出上写入数据。 它们是循环链接的,第一个的输出是第二个输入,另一个是输入。在Linux上由两个命名管道(FIFO)循环链接的两个过滤器
这里是第一过滤器(AC)的代码:
#include <stdio.h>
int main(void ){
FILE* ferr = fopen("/dev/stderr", "w");
double d;
fprintf(ferr,"A is going to write\n");
printf("%lf\n",1.);
fprintf(ferr,"A wrote %lf\n",1.);
while(1){
fprintf(ferr,"A is going to read\n");
if(scanf("%lf",&d) == EOF){
break;
}
fprintf(ferr,"A recieved : %lf\n",d);
d += 1;
fprintf(ferr,"A is going to write\n");
printf("%lf\n",d);
fprintf(ferr,"A wrote %lf\n",d);
}
return 0;
}
这里是第二滤波器的码(BC):
#include <stdio.h>
int main(void ){
FILE* ferr = fopen("/dev/stderr", "w");
double d;
while(1){
fprintf(ferr,"B is going to read\n");
if(scanf("%lf",&d) == EOF){
break;
}
fprintf(ferr,"B recieved : %lf\n",d);
d += 1;
fprintf(ferr,"B is going to write\n");
printf("%lf\n",d);
fprintf(ferr,"B wrote %lf\n",d);
}
return 0;
}
我编译(gcc -o A a.c && gcc -o B b.c
),创建两个fifos(mkfifo b2a ; mkfifo a2b
),运行终端中的第一个程序(cat a2b | ./B > b2a
),打开一个新终端并运行第二个程序(cat b2a | ./A > a2b
)。
我所期望的是一个无限循环,A和B依次递增,但我得到的是B被卡住了,无法读取A写的内容。
在我推出B中的术语,我得到:
B is going to read
在我发起了一个终端,我得到:
A is going to write
A wrote 1.000000
A is going to read
如果我使用lsof的:
lsof b2a a2b
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
cat 24382 john doe 3r FIFO 0,22 0t0 282149936 a2b
B 24383 john doe 1w FIFO 0,22 0t0 282149934 b2a
cat 24413 john doe 3r FIFO 0,22 0t0 282149934 b2a
A 24414 john doe 1w FIFO 0,22 0t0 282149936 a2b
为什么我没有得到我的预期?
在此先感谢。
谢谢。我添加了fflush(NULL);每个printf之后,它现在工作。 – user589082 2011-01-25 15:11:12