Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find next available file descriptor in Bash? [duplicate]

How can I figure out if a file descriptor is currently in use in Bash? For example, if I have a script that reads, writes, and closes fd 3, e.g.

exec 3< <(some command here)
...
cat <&3
exec 3>&-

what's the best way to ensure I'm not interfering with some other purpose for the descriptor that may have been set before my script runs? Do I need to put my whole script in a subshell?

like image 749
Kvass Avatar asked Jan 12 '17 01:01

Kvass


People also ask

How do I check if a file descriptor exists?

fcntl(fd, F_GETFD) is the canonical cheapest way to check that fd is a valid open file descriptor. If you need to batch-check a lot, using poll with a zero timeout and the events member set to 0 and checking for POLLNVAL in revents after it returns is more efficient.

How do I use file descriptors in bash?

When bash starts it opens the three standard file descriptors: stdin (file descriptor 0), stdout (file descriptor 1), and stderr (file descriptor 2). You can open more file descriptors (such as 3, 4, 5, ...), and you can close them. You can also copy file descriptors. And you can write to them and read from them.

How do I find open file descriptors?

In the /proc pseudo filesystem, we can find the open file descriptors under /proc/<pid>/fd/ where <pid> is the PID of a given process. Thus, we have to determine the process identification number (PID) of a process to look at its open file descriptors.

Can you have more than one file descriptor point to the same file?

One process can have multiple file descriptors point to the same entry (e.g., as a result of a call to dup() ) Multiple processes (e.g., a parent and child) can have file descriptors that point to the same entry.


1 Answers

If you do not care if the file descriptor is above 9, you may ask the shell itself to provide one. Of course, the fd is guaranteed to be free by the own shell.

Feature available since bash 4.1+ (2009-12-31) {varname} style automatic file descriptor allocation

$ exec {var}>hellofile
$ echo "$var"
15

$ echo "this is a test" >&${var}
$ cat hellofile
this is a test

$ exec {var}>&-                      # to close the fd.

In fact, in linux, you can see the open fds with:

$ ls /proc/$$/fd
0 1 2 255
like image 91
IsaaC Avatar answered Sep 30 '22 11:09

IsaaC