利用FIFO编写一个Server/Client程序,在客户端输入一个文件名,通过管道把文件名提交给服务器,服务器接受请求若文件存在则返回相应文件内容,否则返回相应错误信息。
/*file:fifo_cs.h*/
#ifndef FIFO_CS_H
#define FIFO_CS_H
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#define SERVER_FIFO "SFIFO"
#define CLIENT_FIFO "CFIFO"
#endif
//end of fifo_cs.h
/*file :fifo_s.c*/
#include"fifo_cs.h"
int main(){
int fdserver,server;
int fdclient;
char strS[BUFSIZ],strC[32],client_fifo_name[32],str[80];
FILE *fp;
mkfifo(SERVER_FIFO,0660);
if(fdserver=open(SERVER_FIFO,O_RDWR)==-1){
printf("Server :Can not open fifo!/n");
exit(1);
}
server=open(CLIENT_FIFO,O_RDWR);
read(server,strC,32);
if((fp=fopen(strC,"r+"))==NULL)
strcpy(strS,"Can not open file./n");
while(!feof(fp)){
if(fgets(str,80,fp))
strcat(strS,str);
}
sprintf(client_fifo_name,"%s",strC);
if((fdclient=open(client_fifo_name,O_WRONLY))==-1)
write(fdclient,strS,BUFSIZ);
close(fdclient);
close(fdserver);
return 0;
}
//end of fifo_s.c
/*file :fifo_c.c*/
#include"fifo_cs.h"
int main(){
int fdserver;
int fdclient,client;
char strS[BUFSIZ];
char strC[32];
char client_fifo_name[32];
if((fdserver=open(SERVER_FIFO,O_RDWR))==-1){
printf("Server not active!/n");
exit(1);
}
printf("Enter filename: ");
gets(strC);
sprintf(client_fifo_name,"%s",strC);
mkfifo(client_fifo_name,0660);
if((fdclient=open(client_fifo_name,O_RDWR))==-1){
close(fdserver);
printf("Can not open fifo !/n");
exit(1);
}
mkfifo(CLIENT_FIFO,0660);
client=open(CLIENT_FIFO,O_RDWR);
write(client,strC,32);
read(fdclient,strS,BUFSIZ);
printf("Client :Get server message :%s/n",strS);
close(fdserver);
close(fdclient);
unlink(client_fifo_name);
return 0;
}
// end of fifo_c.c
运行服务器:gcc fifo_s.c(回车)
运行客户端:gcc fifo_c.c(回车)
./a.out(回车)
输出: Enter filename:
输入文件名回车,如果文件存在则输出:
Client :Get server message :+文件内容
否则输出: Can not open file.
FIFO是一个能在互不相关进程之间传送数据的特殊文件。一个或多个进程向内写入数据,在另一端由一个进程负责读出。我们可以通过FIFO来建立无关进程之间的数据通信。