close() - delete a descriptor
#include <unistd.h>
int close (int d)
The close(2) call deletes the file descriptor d and makes it available for re-use. If the calling process owns any outstanding record locks on the file indicated by d, the call unlocks them.
When all of the file descriptors pointing to a file are deleted, the file is removed. If the file is a pipe or a FIFO, any data remaining in the pipe or FIFO is discarded. For example, on the last close of a file the current seek pointer associated with the file is lost. On the last close of a socket(2), the associated naming information and queued data are discarded.
When a process exits, all associated file descriptors are freed, but since there is a limit on active descriptors per process, the close(2) function call is useful when a large quantity of file descriptors are being handled.
When a process forks (see fork(2)), all descriptors for the new child process reference the same objects as they did in the parent before the fork. If a new process is then to be run using exec(2), the process would normally inherit these descriptors. Most of the descriptors can be rearranged with dup2(2) or deleted with close(2) before the execve(2) is attempted, but if some of these descriptors will still be needed if the execve(2) fails, it is necessary to arrange for them to be closed if the execve(2) succeeds. To do this, use the call:
fcntl(d, F_SETFD, 1)
which arranges that a descriptor will be closed after a successful
execve; to restore the default (that is, not to close the
descriptor), use the call:
fcntl(d, F_SETFD, 0)
Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned and the global integer variable errno is set to indicate the error.
The close(2) call will fail if:
accept(2)
socket(2)
exec(2)
fcntl(2)
open(2)
pipe(2)