直接上源码
首先是用到的数据结构和头文件的声明和定义
//包含客户端和服务器程序都会用到的数据结构等。为了方便使用,
//也包含了必要的系统头文件
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<limits.h>
#include<sys/types.h>
#include<sys/stat.h>
#define SERVER_FIFO_NAME "/tmp/serv_fifo"
#define CLIENT_FIFO_NAME "/tmp/cli_%d_fifo"
#define BUFFER_SIZE 20
struct data_to_pass_st{
pid_t client_pid;
char some_data[BUFFER_SIZE + 1];
};
服务器端的代码:
#include <iostream>
#include"client.h"
#include<ctype.h>
using namespace std;
//在服务器程序中,我们创建并打开服务器管道.被设置为只读的阻塞模式
//在稍作袖子后,服务器开始读取客户端发来的数据,这些数据是采用data_to_pass_st结构
int main()
{
int server_fifo_fd , client_fifo_fd;
struct data_to_pass_st my_data;
int read_res;
char client_fifo[256];
char* tmp_char_ptr;
mkfifo(SERVER_FIFO_NAME , 0777);
server_fifo_fd = open(SERVER_FIFO_NAME , O_RDONLY);
if(server_fifo_fd == -1)
{
fprintf( stderr, "Server fifo failure\n");
exit(EXIT_FAILURE);
}
sleep(10);
do{
read_res = read(server_fifo_fd , &my_data , sizeof(my_data));
if(read_res > 0){
tmp_char_ptr = my_data.some_data;
while(*tmp_char_ptr){
//对从客户端读取到的数据进行处理,把some_data中的左右字符全部转化为大写,并且把CLIENT——FIFO——NAME 和client_pid结合到一起
*tmp_char_ptr = toupper(*tmp_char_ptr);
tmp_char_ptr++;
}
sprintf(client_fifo , CLIENT_FIFO_NAME , my_data.client_pid);
//以只写的方式打开客户通道,把经过处理的数据发送出去。最后,关闭服务器管道文件的文件描述符,删除FIFO文件,退出程序
client_fifo_fd = open(client_fifo , O_WRONLY);
if(client_fifo_fd != -1){
write(client_fifo_fd , &my_data , sizeof(my_data));
close(client_fifo_fd);
}
}
}while(read_res > 0);
close(server_fifo_fd);
unlink(SERVER_FIFO_NAME);
exit(EXIT_SUCCESS);
//return 0;
}
客户端的代码:
#include"client.h"
#include<ctype.h>
int main(){
int server_fifo_fd , client_fifo_fd;
struct data_to_pass_st my_data;
int times_to_send;
char client_fifo[256];
server_fifo_fd = open(SERVER_FIFO_NAME , O_WRONLY);
if(server_fifo_fd == -1){
fprintf(stderr , "Sorry , no server!\n");
exit(EXIT_FAILURE);
}
my_data.client_pid = getpid();
sprintf(client_fifo , CLIENT_FIFO_NAME , my_data.client_pid);
if(mkfifo(client_fifo , 0777) == -1){
fprintf(stderr , "Sorry , Can't make %s\n" , client_fifo);
exit(EXIT_FAILURE);
}
//这部分有5次循环,在每次循环中,客户将数据发送给服务器,然后打开客户FIFO(只读,阻塞模式)b并读回数据。在程序的最后,关闭服务器FIFO并将客户端的FIFO文件从系统中删除
for(times_to_send = 0 ; times_to_send < 5 ; times_to_send++){
sprintf(my_data.some_data , "Hello from %d" , my_data.client_pid);
printf("%d sent %s" , my_data.client_pid , my_data.some_data);
write(server_fifo_fd , &my_data , sizeof(my_data));
client_fifo_fd = open(client_fifo , O_RDONLY);
if(client_fifo_fd != -1){
if(read(client_fifo_fd , &my_data , sizeof(my_data)) > 0){
printf("received: %s\n" , my_data.some_data);
}
close(client_fifo_fd);
}
}
close(server_fifo_fd);
unlink(client_fifo);
exit(EXIT_SUCCESS);
}