利用FIFO編寫一個Server/Client程式,在用戶端輸入一個檔案名,通過管道把檔案名送出給伺服器,伺服器接受請求若檔案存在則傳回相應檔案内容,否則傳回相應錯誤資訊。
#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 #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 #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來建立無關程序之間的資料通信。