views:

56

answers:

2

My understanding was that one could not control the file descriptor (integer) assigned by the OS when opening a new file using open(). How then is it possible in a bash shell to assign a specific file descriptor using a command like

exec 5>&1

(I suppose I could find out by reading the bash sources...)

+3  A: 

See the dup2 Unix system call.

Alex Martelli
This explains how I can dup 2 to 5, but how do I know that 5 is available? What if it is already in use?
c-urchin
http://www.opengroup.org/onlinepubs/9699919799/functions/dup.html`If fildes2 is already a valid open file descriptor, it shall be closed first, unless fildes is equal to fildes2 in which case dup2() shall return fildes2 without closing it.`
R..
+1  A: 

Also, file descriptors are assigned sequentially, so if you know 0, 1, 2, ..., n are already opened and none of them have been closed, the next will be n+1.

R..
Fine, but how can bash be certain that 5 is not already opened? (And what does exec do if it is?)
c-urchin
Bash probably uses `dup2`. And it's careful not to have random file descriptors open when it forks a child process to run a command.
R..
@c-urchin: if you haven't opened 5, it is unlikely that it will be in use.
bstpierre