我試圖在使用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