进程间通信中用有名管道实现两个进程间的通信交流功能

1.主要实现

lucy进程和pete进程间的通信交流。
代码就在这里,我自己在测试时遇到过bug,大家一块交流改进。
pete部分:

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

int main(int argc, char const *argv[])
{
int fd;
char buf[40];
pid_t pid=fork();
if(pid>0)
{
while(1)
{
mkfifo("fifo1",0777);
fd=open("./fifo1",O_WRONLY,0666);
if(fd<0)
{
perror("open error");
exit(0);
}
//pete发送消息给lucy
printf("pete:");
//fflush(stdout);
scanf("%s",&buf);
write(fd,buf,sizeof(buf));

	}
}
if(pid==0)
{	while(1)
	{
	mkfifo("fifo",0777);
	fd=open("./fifo",O_RDONLY,0666);
	if(fd<0)
	{
		perror("open error");
		exit(0);
	}
	//pete接收lucy的消息
	memset(buf,0,sizeof(buf));
	read(fd,buf,sizeof(buf));
	printf("\r  lucy :%s\n",buf);
	
	}

	_exit(0);

}
close(fd);
return 0;
}


lucy部分:

//lucy
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int fd;
char buf[40];
pid_t pid=fork();
if(pid>0)
{
while(1)
{
mkfifo("fifo",0777);
fd=open("./fifo",O_WRONLY,0666);
if(fd<0)
{
perror(“open error”);
exit(0);
}
//lucy发送消息给pete
printf("lucy:");
fflush(stdout);
scanf("%s",&buf);
write(fd,buf,sizeof(buf));

	}
}

if(pid==0)
{	while(1)
	{
	mkfifo("fifo1",0777);
	fd=open("./fifo1",O_RDONLY,0666);
	if(fd<0)
	{
		perror("open error");
		exit(0);
	}
	//接收pete的消息
	memset(buf,0,sizeof(buf));
	read(fd,buf,sizeof(buf));
	printf("\r  pete :%s\n",buf);
	
	}

	_exit(0);
}
close(fd);
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值