利用FIFO编写一个Server/Client程序

利用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来建立无关进程之间的数据通信。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值