操作系统 管道及其实现

本文介绍了操作系统中管道的概念,并提供了多个关于UNIX和Linux管道应用的教程链接,包括Shell实现、命令解析、简易Shell实现以及不同类型的管道通信实验。

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

/*7.“grep –o”不会输出包含某字符串的行,而只会把匹配的字符串输出(有几个匹配就输出几次,且每行输出一个匹配字符串),
因而可以用 “grep  –o  xxx  file | wc -l”来统计文件file中“xxx”字符串出现了多少次。
请用多进程pipe程序实现该功能(此前先用which命令查一下grep命令和wc命令在哪个目录),
要求:创建一个文本文件为zhangsan,自己在该文件中输入若干数目的字符串“zhangsan”,将其作为操作的原材料。
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<unistd.h>
#define MSGSIZE 24

int main(int argc,char *argv[])
{
	int status;
	int pid[2],pipe_fd[2];
	
	char *prog1_argv[]={"/bin/grep","-o",argv[1],argv[2],NULL};
	char *prog2_argv[]={"/usr/bin/wc","-l",NULL};
	
	//create the pipe
	if(pipe(pipe_fd)<0)
	{
		perror("pipe failed\n");
		exit(errno);
	}
	//兄弟之间管道
	if((pid[0]=fork())<0)
	{
		perror("fork failed\n");
		exit(errno);
	}
	//pid[0]==0,即进入子进程
	if(!pid[0])
	{
		close(pipe_fd[0]);
		dup2(pipe_fd[1],1);//pipe_fd[1]指向STDOUT_FILENO,即输出重定向
		close(pipe_fd[1]);
		//装载一个新的程序,并将其转换到调用进程的内存空间,也即向管道写入
		execvp(prog1_argv[0],prog1_argv);
	}
	//回到父进程
	if(pid[0])
	{
		if((pid[1]=fork())<0)
		{
			perror("fork failed\n");
			exit(errno);
		}
		if(!pid[1])
		{
			close(pipe_fd[1]);
			dup2(pipe_fd[0],0);//pipe_fd[0]指向STDIN_FILENO,即输入重定向
			close(pipe_fd[0]);
			//装载一个新的程序,并将其转换到调用进程的内存空间,也即向管道写入
			execvp(prog2_argv[0],prog2_argv);
		}
		close(pipe_fd[0]);
		close(pipe_fd[1]);
		
		waitpid(pid[0],&status,0);
		waitpid(pid[1],&status,0);
	}
	
	return 0;
}

友情链接:
(1)UNIX管道应用及Shell实现(一)-主体框架
https://blog.youkuaiyun.com/crazy_scott/article/details/79548331

(2)UNIX管道应用及Shell实现(二)-命令解析
https://blog.youkuaiyun.com/crazy_scott/article/details/79548325

(3)Linux–实现一个简易的Shell(可以获取命令提示符,支持管道)
https://blog.youkuaiyun.com/xu1105775448/article/details/80311274

(4)Linux进程间通信(二)—管道通信之无名管道及其基础实验
https://blog.youkuaiyun.com/mybelief321/article/details/9073895

(5)Linux进程间通信(三)—管道通信之有名管道及其基础实验
https://blog.youkuaiyun.com/mybelief321/article/details/9075229

(6)Linux进程间通信(九)—综合实验之有名管道通信实验
https://blog.youkuaiyun.com/mybelief321/article/details/9196629

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值