双线程双进程实现终端相互发送信息实时接收信息

该代码展示了两个C程序,每个程序创建两个线程。一个线程从标准输入读取数据并通过一个命名管道(myfifo)写入,另一个线程从管道读取并打印数据。当接收到quit时,进程会退出。两个程序分别以A进程和B进程的角色交互,使用同一对管道进行通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

a.c

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<string.h>
#include<errno.h>
#include<fcntl.h>
#include<pthread.h>
#include<unistd.h>
int fpa,fpb;
char bufw[20]="";
char bufr[20]="";
void* call_back(void* val)
{
	while (1)
	{
		read(fpb,bufr,sizeof(bufr));
		if(!strcasecmp(bufr,"quit")){
			printf("A进程退出\n");
			break;
		}else{
			printf("A进程输出:%s\n",bufr);
		}
		bzero(bufr,sizeof(bufr));
	}
	pthread_exit(NULL);
}
void* call_back_a(void* value)
{
	while (1)
	{
		printf("A进程输入:");
		fgets(bufw,sizeof(bufw),stdin);
		bufw[strlen(bufw)-1]=0;
		write(fpa,bufw,sizeof(bufw));
		if(!strcasecmp(bufw,"quit")){
			printf("A进程退出\n");
			break;
		}	
		bzero(bufw,sizeof(bufw));
	}
	pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
	umask(0);
	if(mkfifo("myfifo",0777)<0)
	{
		if(EEXIST!=errno){
			perror("myfifo");
			return -1;
		}
	}
	if(mkfifo("my_fifo",0777)<0)
	{
		if(EEXIST!=errno){
			perror("my_fifo");
			return -1;
		}
	}
	pthread_t p_a,p_b;
	fpa = open("myfifo",O_WRONLY);
	fpb = open("my_fifo",O_RDONLY);
	pthread_create(&p_a,NULL,call_back,NULL);
	pthread_create(&p_b,NULL,call_back_a,NULL);
	pthread_join(p_a,NULL);
	pthread_join(p_b,NULL);
	close(fpa);
	close(fpb);
	return 0;
}

b.c

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<string.h>
#include<errno.h>
#include<fcntl.h>
#include<pthread.h>
#include<unistd.h>
int fpa,fpb;
char bufw[20]="";
char bufr[20]="";
void* call_back(void* val)
{
	while (1)
	{
		read(fpa,bufr,sizeof(bufr));
		if(!strcasecmp(bufr,"quit")){
			printf("B进程退出\n");
			break;
		}else{
			printf("B进程输出:%s\n",bufr);
		}
		bzero(bufr,sizeof(bufr));
	}
	pthread_exit(NULL);
}
void* call_back_a(void* value)
{
	while (1)
	{
		printf("B进程输入:");
		fgets(bufw,sizeof(bufw),stdin);
		bufw[strlen(bufw)-1]=0;
		write(fpb,bufw,sizeof(bufw));
		if(!strcasecmp(bufw,"quit")){
			printf("B进程退出\n");
			break;
		}	
		bzero(bufw,sizeof(bufw));
	}
	pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
	umask(0);
	if(mkfifo("myfifo",0777)<0)
	{
		if(EEXIST!=errno){
			perror("myfifo");
			return -1;
		}
	}
	if(mkfifo("my_fifo",0777)<0)
	{
		if(EEXIST!=errno){
			perror("my_fifo");
			return -1;
		}
	}
	pthread_t p_a,p_b;
	fpa = open("myfifo",O_RDONLY);
	fpb = open("my_fifo",O_WRONLY);
	pthread_create(&p_a,NULL,call_back,NULL);
	pthread_create(&p_b,NULL,call_back_a,NULL);	
	pthread_join(p_a,NULL);
	pthread_join(p_b,NULL);
	close(fpa);
	close(fpb);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值