应用管道实现父子进程之间的通信

本文通过一个具体的实例演示了如何使用管道实现Linux/Unix环境下父子进程之间的通信。程序首先创建一个管道,然后fork出一个子进程,父进程关闭读端并周期性地向管道写入数据,子进程关闭写端并从管道中读取数据打印到标准输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

应用管道实现父子进程之间的通信
最近在学习Linux/Unix的IPC,而通过管道是其中的一种方式。管道的限制在与,它只能实现父子进程间的通信,通常我们通常会创建一个管道,然后fork出一个子进程,在父进程关掉读端(fd[0]),在子进程里关掉写端(fd[1]),然后在父进程的写端(fd[1])写入数据,在子进程中的读端(fd[0])读数据,这样就实现了父子进程间的通信。
实现代码如下:
#include <iostream>
#include "apue.h"
#include "err_msg.h"
using namespace std;

void print(const char * str)
{
	int pid = getpid();
	cout << str << endl;
	cout << "pid = " << pid << endl;
}

int main()
{
	int 	n;
	int 	fd[2];
	pid_t 	pid;
	char 	line[MAXLINE];
	cout << "MAXLINE = " << MAXLINE << endl;
	
	if (pipe(fd) < 0)
	{
		err_sys("pipe error");
	}
	
	if ((pid = fork()) < 0)
	{
		err_sys("fork error");
	}
	else if (pid > 0)   /*parent process*/
	{
		close(fd[0]);
		while (1) 
		{
			cout << "--------------------------------" << endl;
			print((char *)"parent process");
			cout << "write the data to pipe" << endl;
			write(fd[1], "hello world\n", 12);
			cout << "--------------------------------" << endl;
			sleep(10);
		}
		
	}
	else 				/*child process*/
	{
		close(fd[1]);
		while (1) 
		{
			print((char *)"child process");
			cout << "read the data from pipe" << endl;
			n = read(fd[0], line, MAXLINE);
			write(STDOUT_FILENO, line, n);
			sleep(15);
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值