努力学习Day28【Linux进程间的通信】

接下来的一段时间需要去学习进程间的通信,又是全新的认识了,接着就是线程,我们的目标越来越近,完成我们的Linux学习任务也是指日可待,努力学习吧!

pipe:

这个命令也需要请出来我们的老演员man,使用man 2 pipe查看pipe命令如何使用:

 知道该如何使用之后我们就需要知道运用在哪里?没错,就是我们的fork函数父子进程之中试试:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
	//int pipe(int pipefd[2]);
	int fd[2]; //0 read,1 write
	int pid;
	char buf[128];
	if(pipe(fd) == -1)
	{
		printf("the pro error,open failed!\n");
	}

	pid=fork();

	if(pid<0)
	{printf("creat child fork failed!\n");}
	else if(pid>0)
	{
		printf("this is father pro!\n");
		close(fd[0]); //在父进程中关闭管道fd0
		write(fd[1],"hello from father",strlen("hello from father"));//写操作,写入里面的字节到管道1
	}	
	else
	{
		printf("this is child pro!\n");
		close(fd[1]); //关闭写操作
		read(fd[0],buf,128); //从管道fd0中读取到buf之中
		printf("read from father: %s\n",buf);//输出打印
	}
	return 0;
}

让我们看看结果:

父进程中写入的东西,在子进程中也读取到了。 完成!这就是管道之间的通信。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值