我正在使用fifo on c编写一个简单的客户端 - 服务器通信程序,
我理解O_WROLNY和O_RDONLY是如何工作的(事实是双方都需要打开,否则他们会阻止这个过程)
在我成功写入client_to_server管道之后,服务器端read()仍然被阻止,下面是我的代码,请抢劫:)
Server.c:
void initialization(){
int c_to_s,s_to_c;
int readError;
char* clientFifo = "client_to_server_fifo";
char* serverFifo = "server_to_client_fifo";
char buf[BUFSIZ];
if(mkfifo(serverFifo,0666) < 0)
perror("Cannot create serverFifo.");
if(s_to_c = open(serverFifo, O_WRONLY) == -1)
perror("Cannot open serverFifo.");
if(mkfifo(clientFifo,0666) < 0)
perror("Cannot create clientFifo.");
if(c_to_s = open(clientFifo, O_RDONLY) == -1)
perror("Cannot open clientFifo.");
printf("Server ON.\n");
while(1){
printf("1\n");
if(readError = read(c_to_s,buf,BUFSIZ) == -1)
perror("Cannot read client message.");
printf("2\n");
if(strcmp("exit",buf) == 0){
printf("Server OFF.\n");
break;
}else{
printf("Received: %s\n", buf);
printf("Sending back...\n");
write(s_to_c,buf,BUFSIZ);
}
}
close(c_to_s);
close(s_to_c);
unlink(serverFifo);
unlink(clientFifo);
}
int main(){
initialization();
return 0;
}
Client.c:
void initialization(){
char pseudo[MESSAGE_SIZE];
int c_to_s,s_to_c;
int readError;
char* clientFifo = "client_to_server_fifo";
char* serverFifo = "server_to_client_fifo";
char msg[MESSAGE_SIZE] = "";
if(s_to_c = open(serverFifo, O_RDONLY) == -1)
perror("Cannot open serverFifo.");
sleep(1);
if(c_to_s = open(clientFifo, O_WRONLY) == -1)
perror("Cannot open clientFifo.");
printf("Pseudo> ");
scanf("%s",pseudo);
printf("Connected.\n");
while(1){
printf("Input Message -> ");
scanf("%s",msg);
write(c_to_s,msg,sizeof(msg));
perror(" Write:");
memset(msg,'\0',sizeof(msg));
if(readError = read(s_to_c,msg,sizeof(msg)) == -1)
perror(" Read:");
else
printf("...received from server: %s\n", msg);
}
close(c_to_s);
close(s_to_c);
}
int main(){
initialization();
return 0;
}
来自客户流程的输出:
Pseudo> Client
Connected.
Input Message -> Hello
Hello Write:: Success
服务器流程的输出:
Server ON.
1
我认为问题依赖于Server.c第37行。
read()函数如何检测不到客户端的任何输入。