Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does exec {fd}<file assign file descriptor of file to fd?

Tags:

bash

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.

like image 672
mora Avatar asked Oct 22 '25 04:10

mora


1 Answers

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);
like image 195
PSkocik Avatar answered Oct 25 '25 02:10

PSkocik