进程间通信

本文介绍了进程间通信的基础概念,通过管道实现数据传递,并展示了单向和双向通信的代码示例。在单向通信中,管道使得父子进程能够一方向另一方发送消息。然而,直接使用管道进行双向通信会导致死锁,因为先读的进程会清空管道。为了解决这个问题,可以创建两个独立的管道,分别用于不同的数据流向,从而实现双向通信。
摘要由CSDN通过智能技术生成

进程间通信的基本概念

通过管道进行进程间通信

   为了完成进程间通信,需要创建管道。管道并非属于进程的资源,而是和套接字一样,属于操作系统(也就不是fork函数的复制对象)。两个进程通过操作系统提供的内存空间进行通信。

   

//pipe1.c
#include <stdio.h>
#include <unistd.h>
#define BUF_SIZE 30

int main(int argc, char *argv[])
{
	int fds[2];
	char str[]="Who are you?";
	char buf[BUF_SIZE];
	pid_t pid;
	
	pipe(fds);
	pid=fork();  //调用fork函数复制的是用于管道I/O的文件描述符,而非管道
	if(pid==0)
	{
		write(fds[1], str, sizeof(str));
	}
	else
	{
		read(fds[0], buf, BUF_SIZE);
		puts(buf);
	}
	return 0;
}

通过管道进行进程间双向通信

#include <stdio.h>
#include <unistd.h>
#define BUF_SIZE 30

int main(int argc, char *argv[])
{
	int fds[2];
	char str1[]="Who are you?";
	char str2[]="Thank you for your message";
	char buf[BUF_SIZE];
	pid_t pid;

	pipe(fds);
	pid=fork();

	if(pid==0)
	{
		write(fds[1], str1, sizeof(str1));
		//sleep(2);
		read(fds[0], buf, BUF_SIZE);
		printf("Child proc output: %s \n",  buf);
	}
	else
	{
		read(fds[0], buf, BUF_SIZE);
		printf("Parent proc output: %s \n", buf);
		write(fds[1], str2, sizeof(str2));
		//sleep(3);
	}
	return 0;
}

  上面的代码运行后,会发现父进程在无期限等待。原因是向管道传递数据时,先读的进程会把数据取走。子进程读回自己向管道发送的数据,父进程调用read函数后将无期限等待数据进入管道。

为了进行双向通信,需要创建两个管道,各自负责不同的数据流动:

  

#include <stdio.h>
#include <unistd.h>
#define BUF_SIZE 30

int main(int argc, char *argv[])
{
	int fds1[2], fds2[2];
	char str1[]="Who are you?";
	char str2[]="Thank you for your message";
	char buf[BUF_SIZE];
	pid_t pid;
	
	pipe(fds1), pipe(fds2);
	pid=fork();
	
	if(pid==0)
	{
		write(fds1[1], str1, sizeof(str1));
		read(fds2[0], buf, BUF_SIZE);
		printf("Child proc output: %s \n",  buf);
	}
	else
	{
		read(fds1[0], buf, BUF_SIZE);
		printf("Parent proc output: %s \n", buf);
		write(fds2[1], str2, sizeof(str2));
		sleep(3);
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值