Linux C 利用有名管道(FIFO)实现服务器与客户端的交互

//utili.h
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
#define BUF_SIZE 128
/////////////////////////////////////
服务器(ser.c)
#include"utili.h"
int main()
{
	int ret=mkfifo("write_fifo",0755);
	if(ret==-1)
	{
		perror("mkfifo error!\n");
		return -1;
	}
	int write_fd=open("write_fifo",O_WRONLY);
	if(write_fd==-1)
	{
		perror("open write error!\n");
		return -1;
	}
	int read_fd=open("read_fifo",O_RDONLY);
	if(read_fd==-1)
	{
		perror("open read error\n");
		return -1;
	}
	char sendbuf[BUF_SIZE];
	char recvbuf[BUF_SIZE];
	while(1)
	{
		printf("Ser:> ");
		scanf("%s",sendbuf);
		write(write_fd,sendbuf,strlen(sendbuf)+1);
		read(read_fd,recvbuf,BUF_SIZE);
		printf("Cli:>%s\n",recvbuf);
	}
	close(write_fd);
	close(read_fd);
	return 0;
}
//////////////////////////////////////////////////////////////
客户端(cli.c)
#include"utili.h"
int main()
{
	int read_fd=open("write_fifo",O_RDONLY);
	if(read_fd==-1)
	{
		perror("open read error!\n");
		return -1;
	}

	int ret=mkfifo("read_fifo",0755);
	if(ret==-1)
	{
		perror("mkfifo error!\n");
		return -1;
	}
	int write_fd=open("read_fifo",O_WRONLY);
	if(write_fd==-1)
	{
		perror("open write errorr!\n");
		return -1;
	}
	char sendbuf[BUF_SIZE];
	char recvbuf[BUF_SIZE];
	while(1)
	{
		read(read_fd,recvbuf,128);
		printf("Ser:>%s\n",recvbuf);
		printf("Cli:>");
		scanf("%s",sendbuf);
		write(write_fd,sendbuf,strlen(sendbuf)+1);
	}
	close(read_fd);
	close(write_fd);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Henry313/article/details/88926849