shell 如何执行管道命令? [英] How does shell execute piped commands?

查看:55
本文介绍了shell 如何执行管道命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解 shell 如何执行管道命令?例如猫 |更多的.我知道为了执行一个普通的命令 shell 会分叉,执行它然后孩子返回.但是shell内部是如何处理管道命令的执行的呢?

I want to understand that how does shell executes piped commands ? e.g. cat | more. I am aware that for executing a normal command shell does a fork, execute it and then child returns. But how does shell internally handle the execution of piped commands ?

推荐答案

考虑例如 cat |grep,shell首先fork自己启动cat,然后再fork自己启动grep.

Considering for example cat | grep, the shell first forks itself to start cat, and then forks itself once more to start grep.

在两个新创建的进程中调用 exec* 系列函数之一来启动两个程序之前,棘手的部分是设置管道和重定向描述符.pipe(2) 系统调用在分叉之前在 shell 进程中使用,以返回两个孩子都继承的描述符 - 读取端和写入端.

Before calling one of the exec* family of functions in the two newly created processes to start the two programs, the tricky part is setting up the pipe and redirecting the descriptors. The pipe(2) system call is used in the shell process before forking to return a pair of descriptors which both children inherit - a reading end and a writing end.

读端会在第一个进程(cat)中关闭,stdout会使用dup2(2)系统调用重定向到写端.同样,第二个进程(grep)中的写入端将被关闭,stdin将再次使用dup2(2)重定向到读取端.

The reading end will be closed in the first process (cat), and stdout will be redirected to the writing end using the dup2(2) system call. Similarly, the writing end in the second process (grep) will be closed and stdin will be redirected to the reading end again using dup2(2).

这样两个程序都不知道管道,因为它们只处理标准输入/输出.

This way both programs are unaware of a pipe because they just work with the standard input/output.

这篇关于shell 如何执行管道命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆