我正在尝试使用 fifo 在两个进程之间来回发送信息。它可以工作到一定程度,但随后会出现读取块。我怀疑 Process2 是错误所在。
过程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() 调用似乎工作正常,但是下面的 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
然后它就被阻塞了