IO 用有名管道实现不同进程间的通信

1.实现能够随时收发,即AB可以 随时 互相收发消息:提示 用多线程 或者多线程

p1.c

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

char arr[64] = "";
int fp,fd;
pthread_t pth1,pth2;

void* callback1(void* arg)
{
	while(1){
		bzero(arr,sizeof(arr));
		fgets(arr,sizeof(arr),stdin);
		arr[strlen(arr)-1] = '\0';
		write(fp,arr,strlen(arr));
		if(strcmp(arr,"quit")==0)
		{
			break;
		}
	}
	pthread_cancel(pth2);
	return NULL;
}

void* callback2(void* arg)
{
	while(1){
		read(fd,arr,sizeof(arr));
		if(strcmp(arr,"quit")==0)
		{
			break;
		}
		printf("p1.c从管道中读取:%s\n",arr);
		bzero(arr,sizeof(arr));
	}
	pthread_cancel(pth1);
	return NULL;
}
int main(int argc, const char *argv[])
{
	if(mkfifo("./myfifo",0666)<0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	fp = open("./myfifo",O_RDWR);
	if(fp<0)
	{
		perror("open");
		return -1;
	}
	if(mkfifo("./youfifo",0666)<0)
	{
		if(errno != 17)
		{
			perror("youfifo");
			return -1;
		}
	}
	fd = open("./youfifo",O_RDWR);
	if(fp<0)
	{
		perror("open");
		return -1;
	}
	if(pthread_create(&pth1,NULL,callback1,NULL)!=0)
	{
		perror("1");
		return -1;
	}
	if(pthread_create(&pth2,NULL,callback2,NULL)!=0)
	{
		perror("2");
		return -1;
	}
	pthread_join(pth1,NULL);
	pthread_join(pth2,NULL);
	close(fp);
	close(fd);
	return 0;
}

1.c

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

char arr[64] = "";
int fp,fd;
pthread_t pth1,pth2;

void* callback1(void* arg)
{
	while(1){
		read(fp,arr,sizeof(arr));
		if(strcmp(arr,"quit")==0)
		{
			break;
		}
		printf("1.c从管道中读取:%s\n",arr);
		bzero(arr,sizeof(arr));
	}
	pthread_cancel(pth2);
	return NULL;
}

void* callback2(void* arg)
{
	while(1){
		bzero(arr,sizeof(arr));
		fgets(arr,sizeof(arr),stdin);
		arr[strlen(arr)-1] = '\0';
		write(fd,arr,strlen(arr));
		if(strcmp(arr,"quit")==0)
		{
			break;
		}
	}
	pthread_cancel(pth1);
	return NULL;
}
int main(int argc, const char *argv[])
{
	if(mkfifo("./myfifo",0666)<0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	fp = open("./myfifo",O_RDWR);
	if(fp<0)
	{
		perror("open");
		return -1;
	}
	if(mkfifo("./youfifo",0666)<0)
	{
		if(errno != 17)
		{
			perror("mkfifo");
			return -1;
		}
	}
	fd = open("./youfifo",O_RDWR);
	if(fp<0)
	{
		perror("open");
		return -1;
	}
	if(pthread_create(&pth1,NULL,callback1,NULL)!=0)
	{
		perror("1");
		return -1;
	}
	if(pthread_create(&pth2,NULL,callback2,NULL)!=0)
	{
		perror("2");
		return -1;
	}
	pthread_join(pth1,NULL);
	pthread_join(pth2,NULL);
	close(fp);
	close(fd);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值