进程间通信(七)——FIFO应用:服务端与客户端通信

本文介绍了如何使用FIFO进行服务器与客户端的双向通信,包括服务端程序(server.c)和不同类型的客户端程序(client.c, client1.c, client2.c),探讨了从一对一到多对一的通信模式。" 114016883,10537832,Python自制简易计时器,"['Python开发', '时间处理', '定制计时器']

FIFO应用:服务端与客户端通信

FIFO通信应用

  • 服务器/客户端应用程序
    • 服务端、客户端进程通过FIFO实现双向通信
    • 2个客户端进程通过服务端实现双向通信
    • 多个客户端进程通过服务端实现双向通信
  • 服务端、客户端进程通过FIFO实现双向通信
    • 定义两个FIFO
    • fork,父进程用来读,子进程用来写

server.c

/**********************************
*@file client.c
*@brief  
*@author lizhuofan
*@date 2022-03-11
*************************************/

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_SERVER "fifo_server"
#define FIFO_CLIENT "fifo_client"

int main(int argc, char *argv[])
{
    mkfifo(FIFO_SERVER, 0664);
	mkfifo(FIFO_CLIENT, 0664);

	int ret_from_fork;
	ret_from_fork = fork();
	if (ret_from_fork == -1)
	{
		perror("fork");
		exit(EXIT_FAILURE);
	}
	else if (ret_from_fork == 0)  //child process : write
	{
		int fd_fifo_write;
		fd_fifo_write = open(FIFO_CLIENT, O_WRONLY);
		char buf[128];
		while(1)
		{
			memset(buf, 0, 128);
			scanf("%s", buf);
			write(fd_fifo_write, buf, strlen(buf));
		}
		_exit(EXIT_SUCCESS);
	}
	else
	{
		int fd_fifo_read;
		fd_fifo_read = open(FIFO_SERVER, O_RDONLY);
		char buf[128];
		while(1)
		{
			memset(buf, 0, 128);
			if (read(fd_fifo_read, buf, 100) > 0)
				printf("client : %s\n", buf);
		}
		exit(EXIT_SUCCESS);
	}
	return 0;
}

client.c

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_SERVER "
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值