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

a.c

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
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
#include
#include
#include
#include
#include
#include
#include
#include
#include
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;
}

双线程双进程实现终端相互发送信息实时接收信息_第1张图片

你可能感兴趣的:(c语言,c++,算法)