在上述练习的前提下,实现能够随时收发,即AB可以随时互相收发消息

该博客展示了两个进程A和B如何使用FIFO(命名管道)进行通信。每个进程创建并打开两个FIFO,一个用于发送,一个用于接收。在A进程中,用户输入的数据被发送到B进程,同时B进程从FIFO读取数据并打印。当接收到'quit'时,通信结束。这个示例说明了进程间的同步和通信机制。
摘要由CSDN通过智能技术生成

A进程 

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int fd,fd2;
char buf[20]="";
char buf2[20]="";

void* send_A(void *arg){
	while(1){
		bzero(buf,sizeof(buf));
		printf("请输入\n");
		scanf("%s",buf);
		printf("A进程发送了%s\n",buf);
		write(fd,buf,strlen(buf));
		if(0==strncmp(buf,"quit",4)){
			break;
		}
	}
	pthread_exit(NULL);
}

void* receive_A(void *arg){
	while(1){
		bzero(buf2,sizeof(buf2));
		read(fd2,buf2,sizeof(buf2));
		if(0==strncmp(buf2,"quit",4)){
			break;
		}
		printf("A进程接收了%s\n",buf2);
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	umask(0);
	if(mkfifo("./fifo1",0777)<0){
		if(17!=errno){
			perror("mkfifo");
			return -1;
		}
	}
	printf("fifo1 create success\n");
	if(mkfifo("./fifo2",0777)<0){
		if(17!=errno){
			perror("mkfifo");
			return -1;
		}
	}
	printf("fifo2 create success\n");
	fd=open("./fifo1",O_WRONLY);
	fd2=open("./fifo2",O_RDONLY);
	if(fd<0){
		perror("open");
		return -2;
	}
	if(fd2<0){
		perror("open");
		return -2;
	}
	pthread_t tid1,tid2;
	pthread_create(&tid1,NULL,send_A,NULL);
	pthread_create(&tid1,NULL,receive_A,NULL);
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	return 0;
}

B进程

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int fd,fd2;
char buf[20]="";
char buf2[20]="";

void* send_B(void *arg){
	while(1){
		bzero(buf,sizeof(buf));
		printf("请输入\n");
		scanf("%s",buf);
		printf("B进程发送了%s\n",buf);
		write(fd2,buf,strlen(buf));
		if(0==strncmp(buf,"quit",4)){
			break;
		}
	}
	pthread_exit(NULL);
}

void* receive_B(void *arg){
	while(1){
		bzero(buf2,sizeof(buf2));
		read(fd,buf2,sizeof(buf2));
		if(0==strncmp(buf2,"quit",4)){
			break;
		}
		printf("B进程接收了%s\n",buf2);
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	umask(0);
	if(mkfifo("./fifo1",0777)<0){
		if(17!=errno){
			perror("mkfifo");
			return -1;
		}
	}
	printf("fifo1 create success\n");
	if(mkfifo("./fifo2",0777)<0){
		if(17!=errno){
			perror("mkfifo");
			return -1;
		}
	}
	printf("fifo2 create success\n");
	fd=open("./fifo1",O_RDONLY);
	fd2=open("./fifo2",O_WRONLY);
	if(fd<0){
		perror("open");
		return -2;
	}
	if(fd2<0){
		perror("open");
		return -2;
	}
	pthread_t tid1,tid2;
	pthread_create(&tid1,NULL,send_B,NULL);
	pthread_create(&tid1,NULL,receive_B,NULL);
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值