linux使用管道pipe系统调用在兄弟进程之间读写

7 篇文章 0 订阅

题目:

编写一个程序,创建两个子进程,并使用pipe0系统调用,将一个子进程的标准输出连接到另一个子进程的标准输入。(OS: three esay pieces page36)

理论参考:https://www.cnblogs.com/zhangxuan/p/6704915.html
代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
	int fd[2] = {0, 0};
	int sp = pipe(fd);
	if (sp != 0)
	{
		// 创建管道失败
		return 0;
	}
	// 创建两个子进程
	pid_t p1 = fork();
	if (p1 < 0)
	{
		fprintf(stderr, "fork filed p1\n");
	}
	else if (p1 == 0)
	{
		// p1子进程,写数据到管道
		// 关闭读端
		close(fd[0]);
		char *msg = "Hello world!\n";
		write(fd[1], msg, strlen(msg)); // 向管道写
		close(fd[1]); // 关闭写端
		printf("I am p1, I say \"hello world\" to p2.\n");
		return 0; // p1运行完直接退出;否则p1进程会运行pid_t p2 = fork()
	}

	pid_t p2 = fork();
	if (p2 < 0)
	{
		fprintf(stderr, "fork filed p2\n");
	}
	else if (p2 == 0)
	{
		// p2子进程
		// 等待p1进程完成写操作
		waitpid(p1, NULL, 0);
		close(fd[1]); // 关闭写端
		char buf[1024];
		int len = read(fd[0], buf, 1024); // 从管道中读数据
		if (len > 0)
		{
			buf[len] = '\0';
			printf("I am p2, p1 say: %s\n", buf);
		}
		return 0;
	}

	waitpid(p1, NULL, 0);
	waitpid(p2, NULL, 0);
	printf("I am father, everthing is over!\n");
	return 0;
}
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值