I found a code which gets a file descriptor of 'file'. The code is following.
exec {fd}<'file'
Unfortunately, the code did not provide why it can get a file descriptor by exec. Even after I read the manual of bash, I could not understand what command the exec executes here. Someone who knows the mechanism of the code above, please let me know. Thank you very much.
It's a little weird.
Normally when you run a program, you can specify redirections:
cat 0<file #= cat <file
This basically creates a process for cat by forking. It then opens file, dups its filedescriptor onto filedescriptor 0, and then execs cat within the child.
//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);
//..
}
If you instead were to exec cat 0<file, there would be no forking,
and the redirections and the exec call would happen within the current process:
int fd;
fd = open("file", O_RDONLY);
//...
dup2(fd, 0);
//..
execvpl("cat", "cat", (char*)0);
//..
Shells overload exec so that if no program to exec is provided, only the opening and the duping (which together translate to shell redirections) is done within the current process.
That allows you to redirect for the current process:
exec 0<file #standard input is the file "file" from this point forward
Bash and other advanced shells further extend this to allow you to use the exec syntax to simply open a file and get the file descriptor number.
exec {fd}<file
is basically their way of doing:
fd = open("file", O_RDONLY);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With