day6:进程间的通信

发布时间:2024年01月09日

思维导图:

实现多个进程之间的收发信息操作

create.c:

#include <head.h>
int main(int argc, const char *argv[])
{
	if(mkfifo("a_send_b",0664)!=0)
	{
		perror("");
		return -1;
	}
	if(mkfifo("b_send_a",0664)!=0)
	{
		perror("");
		return -1;
	}
	printf("文件创建成功\n");
	getchar();
	system("rm a_send_b b_send_a");
	return 0;
}

a.c:

#include <head.h>
int main(int argc, const char *argv[])
{
	pid_t pid;
	pid=fork();
	if(pid>0)
	{
		//父进程,发送数据
		char wbuf[20];
		int fd_send=-1;
		if((fd_send=open("./a_send_b",O_WRONLY))==-1)
		{
			perror("");
			return -1;
		}

		while(1)
		{

			bzero(wbuf,sizeof(wbuf));
			printf("请输入:");
			fflush(stdout);
			read(0,wbuf,sizeof(wbuf));
			wbuf[strlen(wbuf)-1]='\0';
			write(fd_send,wbuf,sizeof(wbuf));
			if(strcmp(wbuf,"quit")==0)
			{
				break;
			}
		}
	}
	else if(pid==0)
	{
		//子进程,接受数据
		char rbuf[20];
		int fd_rec=-1;
		if((fd_rec=open("./b_send_a",O_RDONLY))==-1)
		{
			perror("");
			return -1;
		}
		while(1)
		{
			bzero(rbuf,sizeof(rbuf));
			read(fd_rec,rbuf,sizeof(rbuf));
			if(strcmp(rbuf,"quit")==0)
			{
				break;
			}
			printf("接收到的数据:%s\n",rbuf);
		}
		exit(EXIT_SUCCESS);
	}
	wait(NULL);
	return 0;
}

b.c:

#include <head.h>
int main(int argc, const char *argv[])
{
	pid_t pid;
	pid=fork();
	if(pid>0)
	{
		//父进程,发送数据
		char wbuf[20];
		int fd_send=-1;
		if((fd_send=open("./b_send_a",O_WRONLY))==-1)
		{
			perror("");
			return -1;
		}

		while(1)
		{

			bzero(wbuf,sizeof(wbuf));
			printf("请输入:");
			fflush(stdout);
			read(0,wbuf,sizeof(wbuf));
			wbuf[strlen(wbuf)-1]='\0';
			write(fd_send,wbuf,sizeof(wbuf));
			if(strcmp(wbuf,"quit")==0)
			{
				break;
			}
		}
	}
	else if(pid==0)
	{
		//子进程,接受数据
		char rbuf[20];
		int fd_rec=-1;
		if((fd_rec=open("./a_send_b",O_RDONLY))==-1)
		{
			perror("");
			return -1;
		}
		while(1)
		{
			bzero(rbuf,sizeof(rbuf));
			read(fd_rec,rbuf,sizeof(rbuf));
			if(strcmp(rbuf,"quit")==0)
			{
				break;
			}
			printf("接收到的数据:%s\n",rbuf);
		}
		exit(EXIT_SUCCESS);
	}
	wait(NULL);
	return 0;
}

文章来源:https://blog.csdn.net/jackwolfskin2/article/details/135465995
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。