在 bash 脚本中使用管道时 find 和 printf 如何工作
假设我在 find 命令中使用 printf ,如下所示:
find ./folder -printf "%f\n" | other command which uses the result of printf
在其他命令部分中,我可能进行排序或类似的操作,
在这种情况下 printf 到底做了什么?它在“|”之后的部分中在哪里打印进程之前的文件名发生?
例如,如果我对文件名进行排序,它会首先对它们进行排序,然后将排序后的它们打印在监视器上,但在此之前, | 之后的部分到底是如何执行的?获取未排序的文件以便对其进行排序?在这种情况下, printf 是否将文件名作为 | 之后的部分的输入?然后是 | 之后的部分打印输出中排序的文件名?
对不起我的英语:(
Suppose I use the printf in the find command like this:
find ./folder -printf "%f\n" | other command which uses the result of printf
in the other command part, I may be having a sort or something similar
what exactly does printf do in this case? where does it print the file names before the process in the part after "|" happens?
if I sort the filenames for example, it will first sort them, and then print them sorted on the monitor, but before that, how exactly does the part after | get the files unsorted in order to sort them? does the printf in this case give the filenames as input to the part after | and then the part after | prints the file names sorted in the output?
sorry for my english :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 shell 调用
pipe()
创建两个文件描述符。写入一个缓冲区中的数据可以被另一个缓冲区读取。然后它调用fork()
为find
命令创建一个新进程。在fork()
之后,它关闭stdout
(始终 fd 1)并使用dup2()
将管道的一端复制到标准输出。然后它使用
执行相同的操作,以便使用连接到管道另一端的 fd 0 创建它。exec()
运行find
(用find
替换子进程中 shell 的副本)。当find
运行时,它只是像平常一样打印到stdout
,但它从 shell 继承了它,使其成为管道。同时,shell 使用stdin
对其他命令...Your shell calls
pipe()
which creates two file descriptors. Writing into one buffers data in the kernel which is available to be read by the other. Then it callsfork()
to make a new process for thefind
command. After thefork()
it closesstdout
(always fd 1) and usesdup2()
to copy one end of the pipe tostdout
. Then it usesexec()
to runfind
(replacing the copy of the shell in the subprocess withfind
). Whenfind
runs it just prints tostdout
as normal, but it has inherited it from the shell which made it the pipe. Meanwhile the shell is doing the same thing forother command...
withstdin
so that it is created with fd 0 connected to the other end of the pipe.是的,这就是管道的工作原理。第一个过程的输出是第二个过程的输入。在实现方面,shell 创建一个套接字,该套接字从第一个进程的标准输出接收输入,并将输出写入第二个进程的标准输入。
...如果您有此类问题,您也许应该阅读 Unix shell 编程简介。
Yes, that is how pipes work. The output from the first process is the input to the second. In terms of implementation, the shell creates a socket which receives input from the first process from its standard output, and writes output to the second process on its standard input.
... You should perhaps read an introduction to Unix shell programming if you have this type of questions.