1OPEN(2) Linux Programmer's Manual OPEN(2)
2
3
4
6 open, openat, creat - open and possibly create a file
7
9 #include <fcntl.h>
10
11 int open(const char *pathname, int flags);
12 int open(const char *pathname, int flags, mode_t mode);
13
14 int creat(const char *pathname, mode_t mode);
15
16 int openat(int dirfd, const char *pathname, int flags);
17 int openat(int dirfd, const char *pathname, int flags, mode_t mode);
18
19 /* Documented separately, in openat2(2): */
20 int openat2(int dirfd, const char *pathname,
21 const struct open_how *how, size_t size);
22
23 Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
24
25 openat():
26 Since glibc 2.10:
27 _POSIX_C_SOURCE >= 200809L
28 Before glibc 2.10:
29 _ATFILE_SOURCE
30
32 The open() system call opens the file specified by pathname. If the
33 specified file does not exist, it may optionally (if O_CREAT is speci‐
34 fied in flags) be created by open().
35
36 The return value of open() is a file descriptor, a small, nonnegative
37 integer that is an index to an entry in the process's table of open
38 file descriptors. The file descriptor is used in subsequent system
39 calls (read(2), write(2), lseek(2), fcntl(2), etc.) to refer to the
40 open file. The file descriptor returned by a successful call will be
41 the lowest-numbered file descriptor not currently open for the process.
42
43 By default, the new file descriptor is set to remain open across an ex‐
44 ecve(2) (i.e., the FD_CLOEXEC file descriptor flag described in fc‐
45 ntl(2) is initially disabled); the O_CLOEXEC flag, described below, can
46 be used to change this default. The file offset is set to the begin‐
47 ning of the file (see lseek(2)).
48
49 A call to open() creates a new open file description, an entry in the
50 system-wide table of open files. The open file description records the
51 file offset and the file status flags (see below). A file descriptor
52 is a reference to an open file description; this reference is unaf‐
53 fected if pathname is subsequently removed or modified to refer to a
54 different file. For further details on open file descriptions, see
55 NOTES.
56
57 The argument flags must include one of the following access modes:
58 O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-
59 only, write-only, or read/write, respectively.
60
61 In addition, zero or more file creation flags and file status flags can
62 be bitwise-or'd in flags. The file creation flags are O_CLOEXEC,
63 O_CREAT, O_DIRECTORY, O_EXCL, O_NOCTTY, O_NOFOLLOW, O_TMPFILE, and
64 O_TRUNC. The file status flags are all of the remaining flags listed
65 below. The distinction between these two groups of flags is that the
66 file creation flags affect the semantics of the open operation itself,
67 while the file status flags affect the semantics of subsequent I/O op‐
68 erations. The file status flags can be retrieved and (in some cases)
69 modified; see fcntl(2) for details.
70
71 The full list of file creation flags and file status flags is as fol‐
72 lows:
73
74 O_APPEND
75 The file is opened in append mode. Before each write(2), the
76 file offset is positioned at the end of the file, as if with
77 lseek(2). The modification of the file offset and the write op‐
78 eration are performed as a single atomic step.
79
80 O_APPEND may lead to corrupted files on NFS filesystems if more
81 than one process appends data to a file at once. This is be‐
82 cause NFS does not support appending to a file, so the client
83 kernel has to simulate it, which can't be done without a race
84 condition.
85
86 O_ASYNC
87 Enable signal-driven I/O: generate a signal (SIGIO by default,
88 but this can be changed via fcntl(2)) when input or output be‐
89 comes possible on this file descriptor. This feature is avail‐
90 able only for terminals, pseudoterminals, sockets, and (since
91 Linux 2.6) pipes and FIFOs. See fcntl(2) for further details.
92 See also BUGS, below.
93
94 O_CLOEXEC (since Linux 2.6.23)
95 Enable the close-on-exec flag for the new file descriptor.
96 Specifying this flag permits a program to avoid additional fc‐
97 ntl(2) F_SETFD operations to set the FD_CLOEXEC flag.
98
99 Note that the use of this flag is essential in some multi‐
100 threaded programs, because using a separate fcntl(2) F_SETFD op‐
101 eration to set the FD_CLOEXEC flag does not suffice to avoid
102 race conditions where one thread opens a file descriptor and at‐
103 tempts to set its close-on-exec flag using fcntl(2) at the same
104 time as another thread does a fork(2) plus execve(2). Depending
105 on the order of execution, the race may lead to the file de‐
106 scriptor returned by open() being unintentionally leaked to the
107 program executed by the child process created by fork(2). (This
108 kind of race is in principle possible for any system call that
109 creates a file descriptor whose close-on-exec flag should be
110 set, and various other Linux system calls provide an equivalent
111 of the O_CLOEXEC flag to deal with this problem.)
112
113 O_CREAT
114 If pathname does not exist, create it as a regular file.
115
116 The owner (user ID) of the new file is set to the effective user
117 ID of the process.
118
119 The group ownership (group ID) of the new file is set either to
120 the effective group ID of the process (System V semantics) or to
121 the group ID of the parent directory (BSD semantics). On Linux,
122 the behavior depends on whether the set-group-ID mode bit is set
123 on the parent directory: if that bit is set, then BSD semantics
124 apply; otherwise, System V semantics apply. For some filesys‐
125 tems, the behavior also depends on the bsdgroups and sysvgroups
126 mount options described in mount(8).
127
128 The mode argument specifies the file mode bits to be applied
129 when a new file is created. If neither O_CREAT nor O_TMPFILE is
130 specified in flags, then mode is ignored (and can thus be speci‐
131 fied as 0, or simply omitted). The mode argument must be sup‐
132 plied if O_CREAT or O_TMPFILE is specified in flags; if it is
133 not supplied, some arbitrary bytes from the stack will be ap‐
134 plied as the file mode.
135
136 The effective mode is modified by the process's umask in the
137 usual way: in the absence of a default ACL, the mode of the cre‐
138 ated file is (mode & ~umask).
139
140 Note that mode applies only to future accesses of the newly cre‐
141 ated file; the open() call that creates a read-only file may
142 well return a read/write file descriptor.
143
144 The following symbolic constants are provided for mode:
145
146 S_IRWXU 00700 user (file owner) has read, write, and execute
147 permission
148
149 S_IRUSR 00400 user has read permission
150
151 S_IWUSR 00200 user has write permission
152
153 S_IXUSR 00100 user has execute permission
154
155 S_IRWXG 00070 group has read, write, and execute permission
156
157 S_IRGRP 00040 group has read permission
158
159 S_IWGRP 00020 group has write permission
160
161 S_IXGRP 00010 group has execute permission
162
163 S_IRWXO 00007 others have read, write, and execute permission
164
165 S_IROTH 00004 others have read permission
166
167 S_IWOTH 00002 others have write permission
168
169 S_IXOTH 00001 others have execute permission
170
171 According to POSIX, the effect when other bits are set in mode
172 is unspecified. On Linux, the following bits are also honored
173 in mode:
174
175 S_ISUID 0004000 set-user-ID bit
176
177 S_ISGID 0002000 set-group-ID bit (see inode(7)).
178
179 S_ISVTX 0001000 sticky bit (see inode(7)).
180
181 O_DIRECT (since Linux 2.4.10)
182 Try to minimize cache effects of the I/O to and from this file.
183 In general this will degrade performance, but it is useful in
184 special situations, such as when applications do their own
185 caching. File I/O is done directly to/from user-space buffers.
186 The O_DIRECT flag on its own makes an effort to transfer data
187 synchronously, but does not give the guarantees of the O_SYNC
188 flag that data and necessary metadata are transferred. To guar‐
189 antee synchronous I/O, O_SYNC must be used in addition to O_DI‐
190 RECT. See NOTES below for further discussion.
191
192 A semantically similar (but deprecated) interface for block de‐
193 vices is described in raw(8).
194
195 O_DIRECTORY
196 If pathname is not a directory, cause the open to fail. This
197 flag was added in kernel version 2.1.126, to avoid denial-of-
198 service problems if opendir(3) is called on a FIFO or tape de‐
199 vice.
200
201 O_DSYNC
202 Write operations on the file will complete according to the re‐
203 quirements of synchronized I/O data integrity completion.
204
205 By the time write(2) (and similar) return, the output data has
206 been transferred to the underlying hardware, along with any file
207 metadata that would be required to retrieve that data (i.e., as
208 though each write(2) was followed by a call to fdatasync(2)).
209 See NOTES below.
210
211 O_EXCL Ensure that this call creates the file: if this flag is speci‐
212 fied in conjunction with O_CREAT, and pathname already exists,
213 then open() fails with the error EEXIST.
214
215 When these two flags are specified, symbolic links are not fol‐
216 lowed: if pathname is a symbolic link, then open() fails regard‐
217 less of where the symbolic link points.
218
219 In general, the behavior of O_EXCL is undefined if it is used
220 without O_CREAT. There is one exception: on Linux 2.6 and
221 later, O_EXCL can be used without O_CREAT if pathname refers to
222 a block device. If the block device is in use by the system
223 (e.g., mounted), open() fails with the error EBUSY.
224
225 On NFS, O_EXCL is supported only when using NFSv3 or later on
226 kernel 2.6 or later. In NFS environments where O_EXCL support
227 is not provided, programs that rely on it for performing locking
228 tasks will contain a race condition. Portable programs that
229 want to perform atomic file locking using a lockfile, and need
230 to avoid reliance on NFS support for O_EXCL, can create a unique
231 file on the same filesystem (e.g., incorporating hostname and
232 PID), and use link(2) to make a link to the lockfile. If
233 link(2) returns 0, the lock is successful. Otherwise, use
234 stat(2) on the unique file to check if its link count has in‐
235 creased to 2, in which case the lock is also successful.
236
237 O_LARGEFILE
238 (LFS) Allow files whose sizes cannot be represented in an off_t
239 (but can be represented in an off64_t) to be opened. The
240 _LARGEFILE64_SOURCE macro must be defined (before including any
241 header files) in order to obtain this definition. Setting the
242 _FILE_OFFSET_BITS feature test macro to 64 (rather than using
243 O_LARGEFILE) is the preferred method of accessing large files on
244 32-bit systems (see feature_test_macros(7)).
245
246 O_NOATIME (since Linux 2.6.8)
247 Do not update the file last access time (st_atime in the inode)
248 when the file is read(2).
249
250 This flag can be employed only if one of the following condi‐
251 tions is true:
252
253 * The effective UID of the process matches the owner UID of the
254 file.
255
256 * The calling process has the CAP_FOWNER capability in its user
257 namespace and the owner UID of the file has a mapping in the
258 namespace.
259
260 This flag is intended for use by indexing or backup programs,
261 where its use can significantly reduce the amount of disk activ‐
262 ity. This flag may not be effective on all filesystems. One
263 example is NFS, where the server maintains the access time.
264
265 O_NOCTTY
266 If pathname refers to a terminal device—see tty(4)—it will not
267 become the process's controlling terminal even if the process
268 does not have one.
269
270 O_NOFOLLOW
271 If the trailing component (i.e., basename) of pathname is a sym‐
272 bolic link, then the open fails, with the error ELOOP. Symbolic
273 links in earlier components of the pathname will still be fol‐
274 lowed. (Note that the ELOOP error that can occur in this case
275 is indistinguishable from the case where an open fails because
276 there are too many symbolic links found while resolving compo‐
277 nents in the prefix part of the pathname.)
278
279 This flag is a FreeBSD extension, which was added to Linux in
280 version 2.1.126, and has subsequently been standardized in
281 POSIX.1-2008.
282
283 See also O_PATH below.
284
285 O_NONBLOCK or O_NDELAY
286 When possible, the file is opened in nonblocking mode. Neither
287 the open() nor any subsequent I/O operations on the file de‐
288 scriptor which is returned will cause the calling process to
289 wait.
290
291 Note that the setting of this flag has no effect on the opera‐
292 tion of poll(2), select(2), epoll(7), and similar, since those
293 interfaces merely inform the caller about whether a file de‐
294 scriptor is "ready", meaning that an I/O operation performed on
295 the file descriptor with the O_NONBLOCK flag clear would not
296 block.
297
298 Note that this flag has no effect for regular files and block
299 devices; that is, I/O operations will (briefly) block when de‐
300 vice activity is required, regardless of whether O_NONBLOCK is
301 set. Since O_NONBLOCK semantics might eventually be imple‐
302 mented, applications should not depend upon blocking behavior
303 when specifying this flag for regular files and block devices.
304
305 For the handling of FIFOs (named pipes), see also fifo(7). For
306 a discussion of the effect of O_NONBLOCK in conjunction with
307 mandatory file locks and with file leases, see fcntl(2).
308
309 O_PATH (since Linux 2.6.39)
310 Obtain a file descriptor that can be used for two purposes: to
311 indicate a location in the filesystem tree and to perform opera‐
312 tions that act purely at the file descriptor level. The file
313 itself is not opened, and other file operations (e.g., read(2),
314 write(2), fchmod(2), fchown(2), fgetxattr(2), ioctl(2), mmap(2))
315 fail with the error EBADF.
316
317 The following operations can be performed on the resulting file
318 descriptor:
319
320 * close(2).
321
322 * fchdir(2), if the file descriptor refers to a directory
323 (since Linux 3.5).
324
325 * fstat(2) (since Linux 3.6).
326
327 * fstatfs(2) (since Linux 3.12).
328
329 * Duplicating the file descriptor (dup(2), fcntl(2) F_DUPFD,
330 etc.).
331
332 * Getting and setting file descriptor flags (fcntl(2) F_GETFD
333 and F_SETFD).
334
335 * Retrieving open file status flags using the fcntl(2) F_GETFL
336 operation: the returned flags will include the bit O_PATH.
337
338 * Passing the file descriptor as the dirfd argument of openat()
339 and the other "*at()" system calls. This includes linkat(2)
340 with AT_EMPTY_PATH (or via procfs using AT_SYMLINK_FOLLOW)
341 even if the file is not a directory.
342
343 * Passing the file descriptor to another process via a UNIX do‐
344 main socket (see SCM_RIGHTS in unix(7)).
345
346 When O_PATH is specified in flags, flag bits other than
347 O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored.
348
349 Opening a file or directory with the O_PATH flag requires no
350 permissions on the object itself (but does require execute per‐
351 mission on the directories in the path prefix). Depending on
352 the subsequent operation, a check for suitable file permissions
353 may be performed (e.g., fchdir(2) requires execute permission on
354 the directory referred to by its file descriptor argument). By
355 contrast, obtaining a reference to a filesystem object by open‐
356 ing it with the O_RDONLY flag requires that the caller have read
357 permission on the object, even when the subsequent operation
358 (e.g., fchdir(2), fstat(2)) does not require read permission on
359 the object.
360
361 If pathname is a symbolic link and the O_NOFOLLOW flag is also
362 specified, then the call returns a file descriptor referring to
363 the symbolic link. This file descriptor can be used as the
364 dirfd argument in calls to fchownat(2), fstatat(2), linkat(2),
365 and readlinkat(2) with an empty pathname to have the calls oper‐
366 ate on the symbolic link.
367
368 If pathname refers to an automount point that has not yet been
369 triggered, so no other filesystem is mounted on it, then the
370 call returns a file descriptor referring to the automount direc‐
371 tory without triggering a mount. fstatfs(2) can then be used to
372 determine if it is, in fact, an untriggered automount point
373 (.f_type == AUTOFS_SUPER_MAGIC).
374
375 One use of O_PATH for regular files is to provide the equivalent
376 of POSIX.1's O_EXEC functionality. This permits us to open a
377 file for which we have execute permission but not read permis‐
378 sion, and then execute that file, with steps something like the
379 following:
380
381 char buf[PATH_MAX];
382 fd = open("some_prog", O_PATH);
383 snprintf(buf, PATH_MAX, "/proc/self/fd/%d", fd);
384 execl(buf, "some_prog", (char *) NULL);
385
386 An O_PATH file descriptor can also be passed as the argument of
387 fexecve(3).
388
389 O_SYNC Write operations on the file will complete according to the re‐
390 quirements of synchronized I/O file integrity completion (by
391 contrast with the synchronized I/O data integrity completion
392 provided by O_DSYNC.)
393
394 By the time write(2) (or similar) returns, the output data and
395 associated file metadata have been transferred to the underlying
396 hardware (i.e., as though each write(2) was followed by a call
397 to fsync(2)). See NOTES below.
398
399 O_TMPFILE (since Linux 3.11)
400 Create an unnamed temporary regular file. The pathname argument
401 specifies a directory; an unnamed inode will be created in that
402 directory's filesystem. Anything written to the resulting file
403 will be lost when the last file descriptor is closed, unless the
404 file is given a name.
405
406 O_TMPFILE must be specified with one of O_RDWR or O_WRONLY and,
407 optionally, O_EXCL. If O_EXCL is not specified, then linkat(2)
408 can be used to link the temporary file into the filesystem, mak‐
409 ing it permanent, using code like the following:
410
411 char path[PATH_MAX];
412 fd = open("/path/to/dir", O_TMPFILE | O_RDWR,
413 S_IRUSR | S_IWUSR);
414
415 /* File I/O on 'fd'... */
416
417 linkat(fd, "", AT_FDCWD, "/path/for/file", AT_EMPTY_PATH);
418
419 /* If the caller doesn't have the CAP_DAC_READ_SEARCH
420 capability (needed to use AT_EMPTY_PATH with linkat(2)),
421 and there is a proc(5) filesystem mounted, then the
422 linkat(2) call above can be replaced with:
423
424 snprintf(path, PATH_MAX, "/proc/self/fd/%d", fd);
425 linkat(AT_FDCWD, path, AT_FDCWD, "/path/for/file",
426 AT_SYMLINK_FOLLOW);
427 */
428
429 In this case, the open() mode argument determines the file per‐
430 mission mode, as with O_CREAT.
431
432 Specifying O_EXCL in conjunction with O_TMPFILE prevents a tem‐
433 porary file from being linked into the filesystem in the above
434 manner. (Note that the meaning of O_EXCL in this case is dif‐
435 ferent from the meaning of O_EXCL otherwise.)
436
437 There are two main use cases for O_TMPFILE:
438
439 * Improved tmpfile(3) functionality: race-free creation of tem‐
440 porary files that (1) are automatically deleted when closed;
441 (2) can never be reached via any pathname; (3) are not sub‐
442 ject to symlink attacks; and (4) do not require the caller to
443 devise unique names.
444
445 * Creating a file that is initially invisible, which is then
446 populated with data and adjusted to have appropriate filesys‐
447 tem attributes (fchown(2), fchmod(2), fsetxattr(2), etc.)
448 before being atomically linked into the filesystem in a fully
449 formed state (using linkat(2) as described above).
450
451 O_TMPFILE requires support by the underlying filesystem; only a
452 subset of Linux filesystems provide that support. In the ini‐
453 tial implementation, support was provided in the ext2, ext3,
454 ext4, UDF, Minix, and tmpfs filesystems. Support for other
455 filesystems has subsequently been added as follows: XFS (Linux
456 3.15); Btrfs (Linux 3.16); F2FS (Linux 3.16); and ubifs (Linux
457 4.9)
458
459 O_TRUNC
460 If the file already exists and is a regular file and the access
461 mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be
462 truncated to length 0. If the file is a FIFO or terminal device
463 file, the O_TRUNC flag is ignored. Otherwise, the effect of
464 O_TRUNC is unspecified.
465
466 creat()
467 A call to creat() is equivalent to calling open() with flags equal to
468 O_CREAT|O_WRONLY|O_TRUNC.
469
470 openat()
471 The openat() system call operates in exactly the same way as open(),
472 except for the differences described here.
473
474 If the pathname given in pathname is relative, then it is interpreted
475 relative to the directory referred to by the file descriptor dirfd
476 (rather than relative to the current working directory of the calling
477 process, as is done by open() for a relative pathname).
478
479 If pathname is relative and dirfd is the special value AT_FDCWD, then
480 pathname is interpreted relative to the current working directory of
481 the calling process (like open()).
482
483 If pathname is absolute, then dirfd is ignored.
484
485 openat2(2)
486 The openat2(2) system call is an extension of openat(), and provides a
487 superset of the features of openat(). It is documented separately, in
488 openat2(2).
489
491 On success, open(), openat(), and creat() return the new file descrip‐
492 tor (a nonnegative integer). On error, -1 is returned and errno is set
493 to indicate the error.
494
496 open(), openat(), and creat() can fail with the following errors:
497
498 EACCES The requested access to the file is not allowed, or search per‐
499 mission is denied for one of the directories in the path prefix
500 of pathname, or the file did not exist yet and write access to
501 the parent directory is not allowed. (See also path_resolu‐
502 tion(7).)
503
504 EACCES Where O_CREAT is specified, the protected_fifos or pro‐
505 tected_regular sysctl is enabled, the file already exists and is
506 a FIFO or regular file, the owner of the file is neither the
507 current user nor the owner of the containing directory, and the
508 containing directory is both world- or group-writable and
509 sticky. For details, see the descriptions of /proc/sys/fs/pro‐
510 tected_fifos and /proc/sys/fs/protected_regular in proc(5).
511
512 EBUSY O_EXCL was specified in flags and pathname refers to a block de‐
513 vice that is in use by the system (e.g., it is mounted).
514
515 EDQUOT Where O_CREAT is specified, the file does not exist, and the
516 user's quota of disk blocks or inodes on the filesystem has been
517 exhausted.
518
519 EEXIST pathname already exists and O_CREAT and O_EXCL were used.
520
521 EFAULT pathname points outside your accessible address space.
522
523 EFBIG See EOVERFLOW.
524
525 EINTR While blocked waiting to complete an open of a slow device
526 (e.g., a FIFO; see fifo(7)), the call was interrupted by a sig‐
527 nal handler; see signal(7).
528
529 EINVAL The filesystem does not support the O_DIRECT flag. See NOTES
530 for more information.
531
532 EINVAL Invalid value in flags.
533
534 EINVAL O_TMPFILE was specified in flags, but neither O_WRONLY nor
535 O_RDWR was specified.
536
537 EINVAL O_CREAT was specified in flags and the final component ("base‐
538 name") of the new file's pathname is invalid (e.g., it contains
539 characters not permitted by the underlying filesystem).
540
541 EINVAL The final component ("basename") of pathname is invalid (e.g.,
542 it contains characters not permitted by the underlying filesys‐
543 tem).
544
545 EISDIR pathname refers to a directory and the access requested involved
546 writing (that is, O_WRONLY or O_RDWR is set).
547
548 EISDIR pathname refers to an existing directory, O_TMPFILE and one of
549 O_WRONLY or O_RDWR were specified in flags, but this kernel ver‐
550 sion does not provide the O_TMPFILE functionality.
551
552 ELOOP Too many symbolic links were encountered in resolving pathname.
553
554 ELOOP pathname was a symbolic link, and flags specified O_NOFOLLOW but
555 not O_PATH.
556
557 EMFILE The per-process limit on the number of open file descriptors has
558 been reached (see the description of RLIMIT_NOFILE in getr‐
559 limit(2)).
560
561 ENAMETOOLONG
562 pathname was too long.
563
564 ENFILE The system-wide limit on the total number of open files has been
565 reached.
566
567 ENODEV pathname refers to a device special file and no corresponding
568 device exists. (This is a Linux kernel bug; in this situation
569 ENXIO must be returned.)
570
571 ENOENT O_CREAT is not set and the named file does not exist.
572
573 ENOENT A directory component in pathname does not exist or is a dan‐
574 gling symbolic link.
575
576 ENOENT pathname refers to a nonexistent directory, O_TMPFILE and one of
577 O_WRONLY or O_RDWR were specified in flags, but this kernel ver‐
578 sion does not provide the O_TMPFILE functionality.
579
580 ENOMEM The named file is a FIFO, but memory for the FIFO buffer can't
581 be allocated because the per-user hard limit on memory alloca‐
582 tion for pipes has been reached and the caller is not privi‐
583 leged; see pipe(7).
584
585 ENOMEM Insufficient kernel memory was available.
586
587 ENOSPC pathname was to be created but the device containing pathname
588 has no room for the new file.
589
590 ENOTDIR
591 A component used as a directory in pathname is not, in fact, a
592 directory, or O_DIRECTORY was specified and pathname was not a
593 directory.
594
595 ENXIO O_NONBLOCK | O_WRONLY is set, the named file is a FIFO, and no
596 process has the FIFO open for reading.
597
598 ENXIO The file is a device special file and no corresponding device
599 exists.
600
601 ENXIO The file is a UNIX domain socket.
602
603 EOPNOTSUPP
604 The filesystem containing pathname does not support O_TMPFILE.
605
606 EOVERFLOW
607 pathname refers to a regular file that is too large to be
608 opened. The usual scenario here is that an application compiled
609 on a 32-bit platform without -D_FILE_OFFSET_BITS=64 tried to
610 open a file whose size exceeds (1<<31)-1 bytes; see also
611 O_LARGEFILE above. This is the error specified by POSIX.1; in
612 kernels before 2.6.24, Linux gave the error EFBIG for this case.
613
614 EPERM The O_NOATIME flag was specified, but the effective user ID of
615 the caller did not match the owner of the file and the caller
616 was not privileged.
617
618 EPERM The operation was prevented by a file seal; see fcntl(2).
619
620 EROFS pathname refers to a file on a read-only filesystem and write
621 access was requested.
622
623 ETXTBSY
624 pathname refers to an executable image which is currently being
625 executed and write access was requested.
626
627 ETXTBSY
628 pathname refers to a file that is currently in use as a swap
629 file, and the O_TRUNC flag was specified.
630
631 ETXTBSY
632 pathname refers to a file that is currently being read by the
633 kernel (e.g., for module/firmware loading), and write access was
634 requested.
635
636 EWOULDBLOCK
637 The O_NONBLOCK flag was specified, and an incompatible lease was
638 held on the file (see fcntl(2)).
639
640 The following additional errors can occur for openat():
641
642 EBADF dirfd is not a valid file descriptor.
643
644 ENOTDIR
645 pathname is a relative pathname and dirfd is a file descriptor
646 referring to a file other than a directory.
647
649 openat() was added to Linux in kernel 2.6.16; library support was added
650 to glibc in version 2.4.
651
653 open(), creat() SVr4, 4.3BSD, POSIX.1-2001, POSIX.1-2008.
654
655 openat(): POSIX.1-2008.
656
657 openat2(2) is Linux-specific.
658
659 The O_DIRECT, O_NOATIME, O_PATH, and O_TMPFILE flags are Linux-spe‐
660 cific. One must define _GNU_SOURCE to obtain their definitions.
661
662 The O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW flags are not specified in
663 POSIX.1-2001, but are specified in POSIX.1-2008. Since glibc 2.12, one
664 can obtain their definitions by defining either _POSIX_C_SOURCE with a
665 value greater than or equal to 200809L or _XOPEN_SOURCE with a value
666 greater than or equal to 700. In glibc 2.11 and earlier, one obtains
667 the definitions by defining _GNU_SOURCE.
668
669 As noted in feature_test_macros(7), feature test macros such as
670 _POSIX_C_SOURCE, _XOPEN_SOURCE, and _GNU_SOURCE must be defined before
671 including any header files.
672
674 Under Linux, the O_NONBLOCK flag is sometimes used in cases where one
675 wants to open but does not necessarily have the intention to read or
676 write. For example, this may be used to open a device in order to get
677 a file descriptor for use with ioctl(2).
678
679 The (undefined) effect of O_RDONLY | O_TRUNC varies among implementa‐
680 tions. On many systems the file is actually truncated.
681
682 Note that open() can open device special files, but creat() cannot cre‐
683 ate them; use mknod(2) instead.
684
685 If the file is newly created, its st_atime, st_ctime, st_mtime fields
686 (respectively, time of last access, time of last status change, and
687 time of last modification; see stat(2)) are set to the current time,
688 and so are the st_ctime and st_mtime fields of the parent directory.
689 Otherwise, if the file is modified because of the O_TRUNC flag, its
690 st_ctime and st_mtime fields are set to the current time.
691
692 The files in the /proc/[pid]/fd directory show the open file descrip‐
693 tors of the process with the PID pid. The files in the /proc/[pid]/fd‐
694 info directory show even more information about these file descriptors.
695 See proc(5) for further details of both of these directories.
696
697 The Linux header file <asm/fcntl.h> doesn't define O_ASYNC; the (BSD-
698 derived) FASYNC synonym is defined instead.
699
700 Open file descriptions
701 The term open file description is the one used by POSIX to refer to the
702 entries in the system-wide table of open files. In other contexts,
703 this object is variously also called an "open file object", a "file
704 handle", an "open file table entry", or—in kernel-developer parlance—a
705 struct file.
706
707 When a file descriptor is duplicated (using dup(2) or similar), the du‐
708 plicate refers to the same open file description as the original file
709 descriptor, and the two file descriptors consequently share the file
710 offset and file status flags. Such sharing can also occur between pro‐
711 cesses: a child process created via fork(2) inherits duplicates of its
712 parent's file descriptors, and those duplicates refer to the same open
713 file descriptions.
714
715 Each open() of a file creates a new open file description; thus, there
716 may be multiple open file descriptions corresponding to a file inode.
717
718 On Linux, one can use the kcmp(2) KCMP_FILE operation to test whether
719 two file descriptors (in the same process or in two different pro‐
720 cesses) refer to the same open file description.
721
722 Synchronized I/O
723 The POSIX.1-2008 "synchronized I/O" option specifies different variants
724 of synchronized I/O, and specifies the open() flags O_SYNC, O_DSYNC,
725 and O_RSYNC for controlling the behavior. Regardless of whether an im‐
726 plementation supports this option, it must at least support the use of
727 O_SYNC for regular files.
728
729 Linux implements O_SYNC and O_DSYNC, but not O_RSYNC. Somewhat incor‐
730 rectly, glibc defines O_RSYNC to have the same value as O_SYNC.
731 (O_RSYNC is defined in the Linux header file <asm/fcntl.h> on HP PA-
732 RISC, but it is not used.)
733
734 O_SYNC provides synchronized I/O file integrity completion, meaning
735 write operations will flush data and all associated metadata to the un‐
736 derlying hardware. O_DSYNC provides synchronized I/O data integrity
737 completion, meaning write operations will flush data to the underlying
738 hardware, but will only flush metadata updates that are required to al‐
739 low a subsequent read operation to complete successfully. Data integ‐
740 rity completion can reduce the number of disk operations that are re‐
741 quired for applications that don't need the guarantees of file integ‐
742 rity completion.
743
744 To understand the difference between the two types of completion, con‐
745 sider two pieces of file metadata: the file last modification timestamp
746 (st_mtime) and the file length. All write operations will update the
747 last file modification timestamp, but only writes that add data to the
748 end of the file will change the file length. The last modification
749 timestamp is not needed to ensure that a read completes successfully,
750 but the file length is. Thus, O_DSYNC would only guarantee to flush
751 updates to the file length metadata (whereas O_SYNC would also always
752 flush the last modification timestamp metadata).
753
754 Before Linux 2.6.33, Linux implemented only the O_SYNC flag for open().
755 However, when that flag was specified, most filesystems actually pro‐
756 vided the equivalent of synchronized I/O data integrity completion
757 (i.e., O_SYNC was actually implemented as the equivalent of O_DSYNC).
758
759 Since Linux 2.6.33, proper O_SYNC support is provided. However, to en‐
760 sure backward binary compatibility, O_DSYNC was defined with the same
761 value as the historical O_SYNC, and O_SYNC was defined as a new (two-
762 bit) flag value that includes the O_DSYNC flag value. This ensures
763 that applications compiled against new headers get at least O_DSYNC se‐
764 mantics on pre-2.6.33 kernels.
765
766 C library/kernel differences
767 Since version 2.26, the glibc wrapper function for open() employs the
768 openat() system call, rather than the kernel's open() system call. For
769 certain architectures, this is also true in glibc versions before 2.26.
770
771 NFS
772 There are many infelicities in the protocol underlying NFS, affecting
773 amongst others O_SYNC and O_NDELAY.
774
775 On NFS filesystems with UID mapping enabled, open() may return a file
776 descriptor but, for example, read(2) requests are denied with EACCES.
777 This is because the client performs open() by checking the permissions,
778 but UID mapping is performed by the server upon read and write re‐
779 quests.
780
781 FIFOs
782 Opening the read or write end of a FIFO blocks until the other end is
783 also opened (by another process or thread). See fifo(7) for further
784 details.
785
786 File access mode
787 Unlike the other values that can be specified in flags, the access mode
788 values O_RDONLY, O_WRONLY, and O_RDWR do not specify individual bits.
789 Rather, they define the low order two bits of flags, and are defined
790 respectively as 0, 1, and 2. In other words, the combination O_RDONLY
791 | O_WRONLY is a logical error, and certainly does not have the same
792 meaning as O_RDWR.
793
794 Linux reserves the special, nonstandard access mode 3 (binary 11) in
795 flags to mean: check for read and write permission on the file and re‐
796 turn a file descriptor that can't be used for reading or writing. This
797 nonstandard access mode is used by some Linux drivers to return a file
798 descriptor that is to be used only for device-specific ioctl(2) opera‐
799 tions.
800
801 Rationale for openat() and other directory file descriptor APIs
802 openat() and the other system calls and library functions that take a
803 directory file descriptor argument (i.e., execveat(2), faccessat(2),
804 fanotify_mark(2), fchmodat(2), fchownat(2), fspick(2), fstatat(2), fu‐
805 timesat(2), linkat(2), mkdirat(2), move_mount(2), mknodat(2),
806 name_to_handle_at(2), open_tree(2), openat2(2), readlinkat(2), re‐
807 nameat(2), statx(2), symlinkat(2), unlinkat(2), utimensat(2), mkfi‐
808 foat(3), and scandirat(3)) address two problems with the older inter‐
809 faces that preceded them. Here, the explanation is in terms of the
810 openat() call, but the rationale is analogous for the other interfaces.
811
812 First, openat() allows an application to avoid race conditions that
813 could occur when using open() to open files in directories other than
814 the current working directory. These race conditions result from the
815 fact that some component of the directory prefix given to open() could
816 be changed in parallel with the call to open(). Suppose, for example,
817 that we wish to create the file dir1/dir2/xxx.dep if the file
818 dir1/dir2/xxx exists. The problem is that between the existence check
819 and the file-creation step, dir1 or dir2 (which might be symbolic
820 links) could be modified to point to a different location. Such races
821 can be avoided by opening a file descriptor for the target directory,
822 and then specifying that file descriptor as the dirfd argument of (say)
823 fstatat(2) and openat(). The use of the dirfd file descriptor also has
824 other benefits:
825
826 * the file descriptor is a stable reference to the directory, even if
827 the directory is renamed; and
828
829 * the open file descriptor prevents the underlying filesystem from be‐
830 ing dismounted, just as when a process has a current working direc‐
831 tory on a filesystem.
832
833 Second, openat() allows the implementation of a per-thread "current
834 working directory", via file descriptor(s) maintained by the applica‐
835 tion. (This functionality can also be obtained by tricks based on the
836 use of /proc/self/fd/dirfd, but less efficiently.)
837
838 The dirfd argument for these APIs can be obtained by using open() or
839 openat() to open a directory (with either the O_RDONLY or the O_PATH
840 flag). Alternatively, such a file descriptor can be obtained by apply‐
841 ing dirfd(3) to a directory stream created using opendir(3).
842
843 When these APIs are given a dirfd argument of AT_FDCWD or the specified
844 pathname is absolute, then they handle their pathname argument in the
845 same way as the corresponding conventional APIs. However, in this
846 case, several of the APIs have a flags argument that provides access to
847 functionality that is not available with the corresponding conventional
848 APIs.
849
850 O_DIRECT
851 The O_DIRECT flag may impose alignment restrictions on the length and
852 address of user-space buffers and the file offset of I/Os. In Linux
853 alignment restrictions vary by filesystem and kernel version and might
854 be absent entirely. However there is currently no filesystem-indepen‐
855 dent interface for an application to discover these restrictions for a
856 given file or filesystem. Some filesystems provide their own inter‐
857 faces for doing so, for example the XFS_IOC_DIOINFO operation in xf‐
858 sctl(3).
859
860 Under Linux 2.4, transfer sizes, the alignment of the user buffer, and
861 the file offset must all be multiples of the logical block size of the
862 filesystem. Since Linux 2.6.0, alignment to the logical block size of
863 the underlying storage (typically 512 bytes) suffices. The logical
864 block size can be determined using the ioctl(2) BLKSSZGET operation or
865 from the shell using the command:
866
867 blockdev --getss
868
869 O_DIRECT I/Os should never be run concurrently with the fork(2) system
870 call, if the memory buffer is a private mapping (i.e., any mapping cre‐
871 ated with the mmap(2) MAP_PRIVATE flag; this includes memory allocated
872 on the heap and statically allocated buffers). Any such I/Os, whether
873 submitted via an asynchronous I/O interface or from another thread in
874 the process, should be completed before fork(2) is called. Failure to
875 do so can result in data corruption and undefined behavior in parent
876 and child processes. This restriction does not apply when the memory
877 buffer for the O_DIRECT I/Os was created using shmat(2) or mmap(2) with
878 the MAP_SHARED flag. Nor does this restriction apply when the memory
879 buffer has been advised as MADV_DONTFORK with madvise(2), ensuring that
880 it will not be available to the child after fork(2).
881
882 The O_DIRECT flag was introduced in SGI IRIX, where it has alignment
883 restrictions similar to those of Linux 2.4. IRIX has also a fcntl(2)
884 call to query appropriate alignments, and sizes. FreeBSD 4.x intro‐
885 duced a flag of the same name, but without alignment restrictions.
886
887 O_DIRECT support was added under Linux in kernel version 2.4.10. Older
888 Linux kernels simply ignore this flag. Some filesystems may not imple‐
889 ment the flag, in which case open() fails with the error EINVAL if it
890 is used.
891
892 Applications should avoid mixing O_DIRECT and normal I/O to the same
893 file, and especially to overlapping byte regions in the same file.
894 Even when the filesystem correctly handles the coherency issues in this
895 situation, overall I/O throughput is likely to be slower than using ei‐
896 ther mode alone. Likewise, applications should avoid mixing mmap(2) of
897 files with direct I/O to the same files.
898
899 The behavior of O_DIRECT with NFS will differ from local filesystems.
900 Older kernels, or kernels configured in certain ways, may not support
901 this combination. The NFS protocol does not support passing the flag
902 to the server, so O_DIRECT I/O will bypass the page cache only on the
903 client; the server may still cache the I/O. The client asks the server
904 to make the I/O synchronous to preserve the synchronous semantics of
905 O_DIRECT. Some servers will perform poorly under these circumstances,
906 especially if the I/O size is small. Some servers may also be config‐
907 ured to lie to clients about the I/O having reached stable storage;
908 this will avoid the performance penalty at some risk to data integrity
909 in the event of server power failure. The Linux NFS client places no
910 alignment restrictions on O_DIRECT I/O.
911
912 In summary, O_DIRECT is a potentially powerful tool that should be used
913 with caution. It is recommended that applications treat use of O_DI‐
914 RECT as a performance option which is disabled by default.
915
917 Currently, it is not possible to enable signal-driven I/O by specifying
918 O_ASYNC when calling open(); use fcntl(2) to enable this flag.
919
920 One must check for two different error codes, EISDIR and ENOENT, when
921 trying to determine whether the kernel supports O_TMPFILE functional‐
922 ity.
923
924 When both O_CREAT and O_DIRECTORY are specified in flags and the file
925 specified by pathname does not exist, open() will create a regular file
926 (i.e., O_DIRECTORY is ignored).
927
929 chmod(2), chown(2), close(2), dup(2), fcntl(2), link(2), lseek(2),
930 mknod(2), mmap(2), mount(2), open_by_handle_at(2), openat2(2), read(2),
931 socket(2), stat(2), umask(2), unlink(2), write(2), fopen(3), acl(5),
932 fifo(7), inode(7), path_resolution(7), symlink(7)
933
935 This page is part of release 5.12 of the Linux man-pages project. A
936 description of the project, information about reporting bugs, and the
937 latest version of this page, can be found at
938 https://www.kernel.org/doc/man-pages/.
939
940
941
942Linux 2021-03-22 OPEN(2)