我找到了一个获取“文件”文件描述符的代码。代码如下。
exec {fd}<'file'
Run Code Online (Sandbox Code Playgroud)
不幸的是,代码没有提供为什么它可以通过exec获取文件描述符。即使我阅读了 bash 的手册,我也无法理解 exec 在这里执行什么命令。如果有人知道上面代码的机制,请告诉我。非常感谢。
有点奇怪。
通常,当您运行程序时,您可以指定重定向:
cat 0<file #= cat <file
Run Code Online (Sandbox Code Playgroud)
cat这基本上为by ing创建了一个进程fork。然后opens file, 它将dup其文件描述符放入文件描述符 0 上,然后放入子描述exec符中。cat
//Equivalent C code:
pid=fork();
//... (=error checking)
if(0==pid){
//child
int fd;
fd = open("file", O_RDONLY);
//...
dup2(fd, 0);
//..
execvpl("cat", "cat", (char*)0);
//..
}
Run Code Online (Sandbox Code Playgroud)
如果您改为exec cat 0<file,则不会有forking,并且重定向和exec调用将在当前进程内发生:
int fd;
fd = open("file", O_RDONLY);
//...
dup2(fd, 0);
//..
execvpl("cat", "cat", (char*)0);
//..
Run Code Online (Sandbox Code Playgroud)
shell 会重载,exec因此如果没有exec提供程序 to ,则只有opening 和duping (一起转换为 shell 重定向)在当前进程内完成。
这允许您重定向当前进程:
exec 0<file #standard input is the file "file" from this point forward
Run Code Online (Sandbox Code Playgroud)
Bash 和其他高级 shell 进一步扩展了这一点,允许您使用exec语法来简单地打开文件并获取文件描述符编号。
exec {fd}<file
Run Code Online (Sandbox Code Playgroud)
基本上他们的做法是:
fd = open("file", O_RDONLY);
Run Code Online (Sandbox Code Playgroud)