Which is the correct way to close a file descriptor?

Which is the correct way to close a file descriptor?

In that aspect, close is a bit like free: it is invalidating the value (file descriptor for close, pointer for free) passed to it. When possible, you could set the file descriptor to -1 (or some other invalid value) after a successful close (2), so code close (fd); fd = -1; for example.

What’s the syntax for closing a bash file?

First, note that the syntax for closing is 5>&- or 6<&-, depending on whether the file descriptor is being read for writing or for reading. There seems to be a typo or formatting glitch in that blog post.

When do you open a file descriptor in Bash?

In the bash tutorial I am reading, it says that if you open a file descriptor for reading, i.e. However, if you open a file descriptor for writing, it must be closed like this: Yet when I look on the internet, I see people opening files and then closing them with this: NOTE: when, according to the tutorial, they should be using exec 3<&1.

When to use a third descriptor in Bash?

Since there are only two standard descriptors for output, a third is needed. You can call exec to open the output files: The remark about efficiency comes in when you have a redirection in a loop, like this (assume the file is empty to begin with):

What happens if FD is the last file descriptor?

If fd is the last file descriptor referring to the underlying open file description (see open (2)), the resources associated with the open file description are freed; if the file descriptor was the last reference to a file which has been removed using unlink (2), the file is deleted. close () returns zero on success.

What happens when you close a file handle?

When you call close, you always close the file handle. When a file handle is closed, the reference count on its open file description is decremented. If it goes to zero, the open file description is also released and the reference count on the file itself is decremented. Only if that goes to zero is the kernel’s file structure freed.

What happens when a record lock is removed?

Any record locks (see fcntl (2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).