服务端负责读取管道中数据并将其打印出来
fifo_pipe_server.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/syslog.h>
#include <signal.h>
#include <errno.h>
#define BUF_LEN PIPE_BUF
#define FIFO_NAME "/var/tmp/fifo_test"
int sigint = 0;
void signal_acquire(int signo)
{
printf("signal SIGINT GET,pless input quit to exit\n");
sigint =1;
}
int main(int argc,char **argv)
{
int send_Num = 0,send_total = 0,read_std_num;
int read_Num = 0,read_total = 0;
char buf[BUF_LEN];
int ret = 0;
int pipefd;
int quit = 0;
// if(signal(SIGINT, signal_acquire) ==SIG_ERR)
// {
// perror("signal SIGINT\n");
// return -1;
// }
struct sigaction action, old_action;
action.sa_handler = signal_acquire;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGINT, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN) {
sigaction(SIGINT, &action, NULL);
}
if(access(FIFO_NAME,F_OK) < 0){
ret = mkfifo(FIFO_NAME, S_IRUSR|S_IWUSR|S_IWGRP);
if (ret < 0){
perror("mkfifo error\n");
return -1;
}
}
pipefd = open(FIFO_NAME,O_WRONLY);
if(pipefd == -1 ){
perror("open /var/tmp/fifo_test \n");
return -1;
}
do{
read_std_num = read(STDIN_FILENO,buf,BUF_LEN);
send_Num = read_std_num;
if(send_Num < 0){
if(errno == EINTR)
{
continue;
}
perror("read STDIN_FILENO");
close(pipefd);
return -1;
}
if(write(pipefd,buf,send_Num)!=send_Num)
{
fprintf(stderr,"Error wirte data to pipefd");
close(pipefd);
return -1;
}
if(strncmp(buf,"quit",4) == 0){
quit = 1;
}
send_total +=send_Num;
// printf("send_total is %d\n",send_total);
}while(!quit);
return 0;
}
客户端负责从标准输入获得数据,通过fifo管道发送给server端
fifo_pipe_client.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/syslog.h>
#include <signal.h>
#define BUF_LEN PIPE_BUF
#define FIFO_NAME "/var/tmp/fifo_test"
int main(int argc,char **argv)
{
int send_Num = 0,send_total = 0;
int read_Num = 0,read_total = 0;
char buf[BUF_LEN];
int ret = 0;
int pipefd;
int quit = 0;
if(access(FIFO_NAME,F_OK) < 0){
ret = mkfifo(FIFO_NAME, S_IRUSR|S_IWUSR|S_IWGRP);
if (ret < 0){
perror("mkfifo error\n");
return -1;
}
}
pipefd = open(FIFO_NAME,O_RDONLY);
if(pipefd == -1 ){
perror("open /var/tmp/fifo_test \n");
return -1;
}
do
{
memset(buf,0,sizeof(buf));
if((read_Num = read(pipefd,buf,BUF_LEN))< 0 ){
fprintf(stderr,"Error wirte data to serverfd");
close(pipefd);
return -1;
}
read_total +=read_Num;
printf("pipe server read is %s\n",buf);
if(strncmp(buf,"quit",4) == 0){
quit = 1;
break;
}
}while(!quit);
return 0;
}
编译的Makefile文件
all:clean fifo_pipe_server fifo_pipe_client
fifo_pipe_server:fifo_pipe_server.c
$(CC) -o fifo_pipe_server fifo_pipe_server.c
fifo_pipe_client:fifo_pipe_client.c
$(CC) -o fifo_pipe_client fifo_pipe_client.c
clean:
rm -f fifo_pipe_server fifo_pipe_client
在linux中运行:
./fifo_pipe_server &
./fifo_pipe_client