1CLOSE(2) Linux Programmer's Manual CLOSE(2)
2
3
4
6 close - close a file descriptor
7
9 #include <unistd.h>
10
11 int close(int fd);
12
14 close() closes a file descriptor, so that it no longer refers to any
15 file and may be reused. Any record locks (see fcntl(2)) held on the
16 file it was associated with, and owned by the process, are removed
17 (regardless of the file descriptor that was used to obtain the lock).
18
19 If fd is the last file descriptor referring to the underlying open file
20 description (see open(2)), the resources associated with the open file
21 description are freed; if the file descriptor was the last reference to
22 a file which has been removed using unlink(2), the file is deleted.
23
25 close() returns zero on success. On error, -1 is returned, and errno
26 is set appropriately.
27
29 EBADF fd isn't a valid open file descriptor.
30
31 EINTR The close() call was interrupted by a signal; see signal(7).
32
33 EIO An I/O error occurred.
34
35 ENOSPC, EDQUOT
36 On NFS, these errors are not normally reported against the first
37 write which exceeds the available storage space, but instead
38 against a subsequent write(2), fsync(2), or close().
39
40 See NOTES for a discussion of why close() should not be retried after
41 an error.
42
44 POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD.
45
47 A successful close does not guarantee that the data has been success‐
48 fully saved to disk, as the kernel uses the buffer cache to defer
49 writes. Typically, filesystems do not flush buffers when a file is
50 closed. If you need to be sure that the data is physically stored on
51 the underlying disk, use fsync(2). (It will depend on the disk hard‐
52 ware at this point.)
53
54 The close-on-exec file descriptor flag can be used to ensure that a
55 file descriptor is automatically closed upon a successful execve(2);
56 see fcntl(2) for details.
57
58 It is probably unwise to close file descriptors while they may be in
59 use by system calls in other threads in the same process. Since a file
60 descriptor may be reused, there are some obscure race conditions that
61 may cause unintended side effects.
62
63 When dealing with sockets, you have to be sure that there is no recv(2)
64 still blocking on it on another thread, otherwise it might block for‐
65 ever, since no more messages will be send via the socket. Be sure to
66 use shutdown(2) to shut down all parts the connection before closing
67 the socket.
68
69 D