我试图在使用fifo的两个进程之间来回发送信息。它工作到一个点,但然后一个阅读块。我怀疑Process2是错误的地方。读取中间值时双向fifo通信块
处理1:
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
main()
{
char oprtr;
int fd1,fd0;
float oprnd1,oprnd2,result;
mkfifo("fifo1",0777);
fd1=open("fifo1",O_RDWR);
printf("fd1:%d\n",fd1);
printf("Add(+)\n");
printf("subtract(-)\n");
printf("multiply(*)\n");
printf("division(/)\n");
printf("Enter operator\n");
scanf("%c",&oprtr);
getchar();
write(fd1,&oprtr,sizeof(oprtr));
printf("Enter oprnd1\n");
scanf("%f",&oprnd1);
getchar();
write(fd1,&oprnd1,sizeof(oprnd1));
fd0=dup(fd1);
printf("Enter oprnd2\n");
scanf("%f",&oprnd2);
getchar();
if(write(fd0,&oprnd2,sizeof(oprnd2))==0)
perror("write : oprnd2:");
else
printf("writing oprnd2 done\n");
read(fd1,&result,sizeof(result));
printf("Result:%f\n",result);
}
过程2:
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
main()
{
int fd2,fd3;
char oprtr;
float oprnd1,oprnd2,result;
fd2=open("fifo1",O_RDWR);
printf("fd2:%d\n",fd2);
read(fd2,&oprtr,sizeof(oprtr));
printf("oprtr:%c\n",oprtr);
read(fd2,&oprnd1,sizeof(oprnd1));
printf("oprnd1:%f\n",oprnd1);
fd3=dup(fd2);
这就是读取功能被阻塞
上述两个读()调用出现工作正常,但以下read()调用被阻止。为什么?
if(read(fd3,&oprnd2,sizeof(oprnd2))==0) ////This is the problem
perror("read : oprnd2:");
else
printf("oprnd2:%f\n",oprnd2);
switch(oprtr)
{
case '+':result=oprnd1+oprnd2;
write(fd2,&result,sizeof(result));break;
case '-':result=oprnd1-oprnd2;
write(fd2,&result,sizeof(result));break;
case '*':result=oprnd1*oprnd2;
write(fd2,&result,sizeof(result));break;
case '/':result=oprnd1/oprnd2;
write(fd2,&result,sizeof(result));break;
default: printf("Wrong Choice\n");break;
}
}
端子1:
Add(+)
subtract(-)
multiply(*)
division(/)
Enter operator
+
Enter oprnd1
14.56
Enter oprnd2
16.44
writing oprnd2 done
Result:16.440089
2号航站楼:
fd2:3
oprtr:+
oprnd1:14.560000
然后,它只是被封锁
看起来您正试图在两个进程之间创建客户端 - 服务器关系。如果你是,而且这是一个严肃的项目(即不只是一个演示或玩具),我建议你考虑使用远程过程调用(RPC)。 – Scott