1FCNTL(2) Linux Programmer's Manual FCNTL(2)
2
3
4
6 fcntl - manipulate file descriptor
7
9 #include <unistd.h>
10 #include <fcntl.h>
11
12 int fcntl(int fd, int cmd, ... /* arg */ );
13
15 fcntl() performs one of the operations described below on the open file
16 descriptor fd. The operation is determined by cmd.
17
18 fcntl() can take an optional third argument. Whether or not this argu‐
19 ment is required is determined by cmd. The required argument type is
20 indicated in parentheses after each cmd name (in most cases, the
21 required type is int, and we identify the argument using the name arg),
22 or void is specified if the argument is not required.
23
24 Certain of the operations below are supported only since a particular
25 Linux kernel version. The preferred method of checking whether the
26 host kernel supports a particular operation is to invoke fcntl() with
27 the desired cmd value and then test whether the call failed with EIN‐
28 VAL, indicating that the kernel does not recognize this value.
29
30 Duplicating a file descriptor
31 F_DUPFD (int)
32 Duplicate the file descriptor fd using the lowest-numbered
33 available file descriptor greater than or equal to arg. This is
34 different from dup2(2), which uses exactly the file descriptor
35 specified.
36
37 On success, the new file descriptor is returned.
38
39 See dup(2) for further details.
40
41 F_DUPFD_CLOEXEC (int; since Linux 2.6.24)
42 As for F_DUPFD, but additionally set the close-on-exec flag for
43 the duplicate file descriptor. Specifying this flag permits a
44 program to avoid an additional fcntl() F_SETFD operation to set
45 the FD_CLOEXEC flag. For an explanation of why this flag is
46 useful, see the description of O_CLOEXEC in open(2).
47
48 File descriptor flags
49 The following commands manipulate the flags associated with a file
50 descriptor. Currently, only one such flag is defined: FD_CLOEXEC, the
51 close-on-exec flag. If the FD_CLOEXEC bit is set, the file descriptor
52 will automatically be closed during a successful execve(2). (If the
53 execve(2) fails, the file descriptor is left open.) If the FD_CLOEXEC
54 bit is not set, the file descriptor will remain open across an
55 execve(2).
56
57 F_GETFD (void)
58 Return (as the function result) the file descriptor flags; arg
59 is ignored.
60
61 F_SETFD (int)
62 Set the file descriptor flags to the value specified by arg.
63
64 In multithreaded programs, using fcntl() F_SETFD to set the close-on-
65 exec flag at the same time as another thread performs a fork(2) plus
66 execve(2) is