1OPEN(3P) POSIX Programmer's Manual OPEN(3P)
2
3
4
6 This manual page is part of the POSIX Programmer's Manual. The Linux
7 implementation of this interface may differ (consult the corresponding
8 Linux manual page for details of Linux behavior), or the interface may
9 not be implemented on Linux.
10
12 open, openat — open file
13
15 #include <sys/stat.h>
16 #include <fcntl.h>
17
18 int open(const char *path, int oflag, ...);
19 int openat(int fd, const char *path, int oflag, ...);
20
22 The open() function shall establish the connection between a file and a
23 file descriptor. It shall create an open file description that refers
24 to a file and a file descriptor that refers to that open file descrip‐
25 tion. The file descriptor is used by other I/O functions to refer to
26 that file. The path argument points to a pathname naming the file.
27
28 The open() function shall return a file descriptor for the named file,
29 allocated as described in Section 2.14, File Descriptor Allocation.
30 The open file description is new, and therefore the file descriptor
31 shall not share it with any other process in the system. The FD_CLOEXEC
32 file descriptor flag associated with the new file descriptor shall be
33 cleared unless the O_CLOEXEC flag is set in oflag.
34
35 The file offset used to mark the current position within the file shall
36 be set to the beginning of the file.
37
38 The file status flags and file access modes of the open file descrip‐
39 tion shall be set according to the value of oflag.
40
41 Values for oflag are constructed by a bitwise-inclusive OR of flags
42 from the following list, defined in <fcntl.h>. Applications shall
43 specify exactly one of the first five values (file access modes) below
44 in the value of oflag:
45
46 O_EXEC Open for execute only (non-directory files). The result
47 is unspecified if this flag is applied to a directory.
48
49 O_RDONLY Open for reading only.
50
51 O_RDWR Open for reading and writing. The result is undefined if
52 this flag is applied to a FIFO.
53
54 O_SEARCH Open directory for search only. The result is unspecified
55 if this flag is applied to a non-directory file.
56
57 O_WRONLY Open for writing only.
58
59 Any combination of the following may be used:
60
61 O_APPEND If set, the file offset shall be set to the end of the
62 file prior to each write.
63
64 O_CLOEXEC If set, the FD_CLOEXEC flag for the new file descriptor
65 shall be set.
66
67 O_CREAT If the file exists, this flag has no effect except as
68 noted under O_EXCL below. Otherwise, if O_DIRECTORY is
69 not set the file shall be created as a regular file; the
70 user ID of the file shall be set to the effective user ID
71 of the process; the group ID of the file shall be set to
72 the group ID of the file's parent directory or to the
73 effective group ID of the process; and the access permis‐
74 sion bits (see <sys/stat.h>) of the file mode shall be
75 set to the value of the argument following the oflag
76 argument taken as type mode_t modified as follows: a bit‐
77 wise AND is performed on the file-mode bits and the cor‐
78 responding bits in the complement of the process' file
79 mode creation mask. Thus, all bits in the file mode whose
80 corresponding bit in the file mode creation mask is set
81 are cleared. When bits other than the file permission
82 bits are set, the effect is unspecified. The argument
83 following the oflag argument does not affect whether the
84 file is open for reading, writing, or for both. Implemen‐
85 tations shall provide a way to initialize the file's
86 group ID to the group ID of the parent directory. Imple‐
87 mentations may, but need not, provide an implementation-
88 defined way to initialize the file's group ID to the
89 effective group ID of the calling process.
90
91 O_DIRECTORY If path resolves to a non-directory file, fail and set
92 errno to [ENOTDIR].
93
94 O_DSYNC Write I/O operations on the file descriptor shall com‐
95 plete as defined by synchronized I/O data integrity com‐
96 pletion.
97
98 O_EXCL If O_CREAT and O_EXCL are set, open() shall fail if the
99 file exists. The check for the existence of the file and
100 the creation of the file if it does not exist shall be
101 atomic with respect to other threads executing open()
102 naming the same filename in the same directory with
103 O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set,
104 and path names a symbolic link, open() shall fail and set
105 errno to [EEXIST], regardless of the contents of the sym‐
106 bolic link. If O_EXCL is set and O_CREAT is not set, the
107 result is undefined.
108
109 O_NOCTTY If set and path identifies a terminal device, open()
110 shall not cause the terminal device to become the con‐
111 trolling terminal for the process. If path does not iden‐
112 tify a terminal device, O_NOCTTY shall be ignored.
113
114 O_NOFOLLOW If path names a symbolic link, fail and set errno to
115 [ELOOP].
116
117 O_NONBLOCK When opening a FIFO with O_RDONLY or O_WRONLY set:
118
119 * If O_NONBLOCK is set, an open() for reading-only
120 shall return without delay. An open() for writing-
121 only shall return an error if no process currently
122 has the file open for reading.
123
124 * If O_NONBLOCK is clear, an open() for reading-only
125 shall block the calling thread until a thread opens
126 the file for writing. An open() for writing-only
127 shall block the calling thread until a thread opens
128 the file for reading.
129
130 When opening a block special or character special file
131 that supports non-blocking opens:
132
133 * If O_NONBLOCK is set, the open() function shall
134 return without blocking for the device to be ready or
135 available. Subsequent behavior of the device is
136 device-specific.
137
138 * If O_NONBLOCK is clear, the open() function shall
139 block the calling thread until the device is ready or
140 available before returning.
141
142 Otherwise, the O_NONBLOCK flag shall not cause an error,
143 but it is unspecified whether the file status flags will
144 include the O_NONBLOCK flag.
145
146 O_RSYNC Read I/O operations on the file descriptor shall complete
147 at the same level of integrity as specified by the
148 O_DSYNC and O_SYNC flags. If both O_DSYNC and O_RSYNC are
149 set in oflag, all I/O operations on the file descriptor
150 shall complete as defined by synchronized I/O data
151 integrity completion. If both O_SYNC and O_RSYNC are set
152 in flags, all I/O operations on the file descriptor shall
153 complete as defined by synchronized I/O file integrity
154 completion.
155
156 O_SYNC Write I/O operations on the file descriptor shall com‐
157 plete as defined by synchronized I/O file integrity com‐
158 pletion.
159
160 The O_SYNC flag shall be supported for regular files,
161 even if the Synchronized Input and Output option is not
162 supported.
163
164 O_TRUNC If the file exists and is a regular file, and the file is
165 successfully opened O_RDWR or O_WRONLY, its length shall
166 be truncated to 0, and the mode and owner shall be
167 unchanged. It shall have no effect on FIFO special files
168 or terminal device files. Its effect on other file types
169 is implementation-defined. The result of using O_TRUNC
170 without either O_RDWR or O_WRONLY is undefined.
171
172 O_TTY_INIT If path identifies a terminal device other than a pseudo-
173 terminal, the device is not already open in any process,
174 and either O_TTY_INIT is set in oflag or O_TTY_INIT has
175 the value zero, open() shall set any non-standard termios
176 structure terminal parameters to a state that provides
177 conforming behavior; see the Base Definitions volume of
178 POSIX.1‐2017, Section 11.2, Parameters that Can be Set.
179 It is unspecified whether O_TTY_INIT has any effect if
180 the device is already open in any process. If path iden‐
181 tifies the slave side of a pseudo-terminal that is not
182 already open in any process, open() shall set any non-
183 standard termios structure terminal parameters to a state
184 that provides conforming behavior, regardless of whether
185 O_TTY_INIT is set. If path does not identify a terminal
186 device, O_TTY_INIT shall be ignored.
187
188 If O_CREAT and O_DIRECTORY are set and the requested access mode is
189 neither O_WRONLY nor O_RDWR, the result is unspecified.
190
191 If O_CREAT is set and the file did not previously exist, upon success‐
192 ful completion, open() shall mark for update the last data access, last
193 data modification, and last file status change timestamps of the file
194 and the last data modification and last file status change timestamps
195 of the parent directory.
196
197 If O_TRUNC is set and the file did previously exist, upon successful
198 completion, open() shall mark for update the last data modification and
199 last file status change timestamps of the file.
200
201 If both the O_SYNC and O_DSYNC flags are set, the effect is as if only
202 the O_SYNC flag was set.
203
204 If path refers to a STREAMS file, oflag may be constructed from O_NON‐
205 BLOCK OR'ed with either O_RDONLY, O_WRONLY, or O_RDWR. Other flag val‐
206 ues are not applicable to STREAMS devices and shall have no effect on
207 them. The value O_NONBLOCK affects the operation of STREAMS drivers and
208 certain functions applied to file descriptors associated with STREAMS
209 files. For STREAMS drivers, the implementation of O_NONBLOCK is device-
210 specific.
211
212 The application shall ensure that it specifies the O_TTY_INIT flag on
213 the first open of a terminal device since system boot or since the
214 device was closed by the process that last had it open. The application
215 need not specify the O_TTY_INIT flag when opening pseudo-terminals. If
216 path names the master side of a pseudo-terminal device, then it is
217 unspecified whether open() locks the slave side so that it cannot be
218 opened. Conforming applications shall call unlockpt() before opening
219 the slave side.
220
221 The largest value that can be represented correctly in an object of
222 type off_t shall be established as the offset maximum in the open file
223 description.
224
225 The openat() function shall be equivalent to the open() function except
226 in the case where path specifies a relative path. In this case the file
227 to be opened is determined relative to the directory associated with
228 the file descriptor fd instead of the current working directory. If the
229 access mode of the open file description associated with the file
230 descriptor is not O_SEARCH, the function shall check whether directory
231 searches are permitted using the current permissions of the directory
232 underlying the file descriptor. If the access mode is O_SEARCH, the
233 function shall not perform the check.
234
235 The oflag parameter and the optional fourth parameter correspond
236 exactly to the parameters of open().
237
238 If openat() is passed the special value AT_FDCWD in the fd parameter,
239 the current working directory shall be used and the behavior shall be
240 identical to a call to open().
241
243 Upon successful completion, these functions shall open the file and
244 return a non-negative integer representing the file descriptor. Other‐
245 wise, these functions shall return -1 and set errno to indicate the
246 error. If -1 is returned, no files shall be created or modified.
247
249 These functions shall fail if:
250
251 EACCES Search permission is denied on a component of the path prefix,
252 or the file exists and the permissions specified by oflag are
253 denied, or the file does not exist and write permission is
254 denied for the parent directory of the file to be created, or
255 O_TRUNC is specified and write permission is denied.
256
257 EEXIST O_CREAT and O_EXCL are set, and the named file exists.
258
259 EINTR A signal was caught during open().
260
261 EINVAL The implementation does not support synchronized I/O for this
262 file.
263
264 EIO The path argument names a STREAMS file and a hangup or error
265 occurred during the open().
266
267 EISDIR The named file is a directory and oflag includes O_WRONLY or
268 O_RDWR, or includes O_CREAT without O_DIRECTORY.
269
270 ELOOP A loop exists in symbolic links encountered during resolution of
271 the path argument, or O_NOFOLLOW was specified and the path
272 argument names a symbolic link.
273
274 EMFILE All file descriptors available to the process are currently
275 open.
276
277 ENAMETOOLONG
278 The length of a component of a pathname is longer than
279 {NAME_MAX}.
280
281 ENFILE The maximum allowable number of files is currently open in the
282 system.
283
284 ENOENT O_CREAT is not set and a component of path does not name an
285 existing file, or O_CREAT is set and a component of the path
286 prefix of path does not name an existing file, or path points to
287 an empty string.
288
289 ENOENT or ENOTDIR
290 O_CREAT is set, and the path argument contains at least one
291 non-<slash> character and ends with one or more trailing <slash>
292 characters. If path without the trailing <slash> characters
293 would name an existing file, an [ENOENT] error shall not occur.
294
295 ENOSR The path argument names a STREAMS-based file and the system is
296 unable to allocate a STREAM.
297
298 ENOSPC The directory or file system that would contain the new file
299 cannot be expanded, the file does not exist, and O_CREAT is
300 specified.
301
302 ENOTDIR
303 A component of the path prefix names an existing file that is
304 neither a directory nor a symbolic link to a directory; or
305 O_CREAT and O_EXCL are not specified, the path argument contains
306 at least one non-<slash> character and ends with one or more
307 trailing <slash> characters, and the last pathname component
308 names an existing file that is neither a directory nor a sym‐
309 bolic link to a directory; or O_DIRECTORY was specified and the
310 path argument resolves to a non-directory file.
311
312 ENXIO O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set,
313 and no process has the file open for reading.
314
315 ENXIO The named file is a character special or block special file, and
316 the device associated with this special file does not exist.
317
318 EOVERFLOW
319 The named file is a regular file and the size of the file cannot
320 be represented correctly in an object of type off_t.
321
322 EROFS The named file resides on a read-only file system and either
323 O_WRONLY, O_RDWR, O_CREAT (if the file does not exist), or
324 O_TRUNC is set in the oflag argument.
325
326 The openat() function shall fail if:
327
328 EACCES The access mode of the open file description associated with fd
329 is not O_SEARCH and the permissions of the directory underlying
330 fd do not permit directory searches.
331
332 EBADF The path argument does not specify an absolute path and the fd
333 argument is neither AT_FDCWD nor a valid file descriptor open
334 for reading or searching.
335
336 ENOTDIR
337 The path argument is not an absolute path and fd is a file
338 descriptor associated with a non-directory file.
339
340 These functions may fail if:
341
342 EAGAIN The path argument names the slave side of a pseudo-terminal
343 device that is locked.
344
345 EINVAL The value of the oflag argument is not valid.
346
347 ELOOP More than {SYMLOOP_MAX} symbolic links were encountered during
348 resolution of the path argument.
349
350 ENAMETOOLONG
351 The length of a pathname exceeds {PATH_MAX}, or pathname resolu‐
352 tion of a symbolic link produced an intermediate result with a
353 length that exceeds {PATH_MAX}.
354
355 ENOMEM The path argument names a STREAMS file and the system is unable
356 to allocate resources.
357
358 EOPNOTSUPP
359 The path argument names a socket.
360
361 ETXTBSY
362 The file is a pure procedure (shared text) file that is being
363 executed and oflag is O_WRONLY or O_RDWR.
364
365 The following sections are informative.
366
368 Opening a File for Writing by the Owner
369 The following example opens the file /tmp/file, either by creating it
370 (if it does not already exist), or by truncating its length to 0 (if it
371 does exist). In the former case, if the call creates a new file, the
372 access permission bits in the file mode of the file are set to permit
373 reading and writing by the owner, and to permit reading only by group
374 members and others.
375
376 If the call to open() is successful, the file is opened for writing.
377
378
379 #include <fcntl.h>
380 ...
381 int fd;
382 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
383 char *pathname = "/tmp/file";
384 ...
385 fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);
386 ...
387
388 Opening a File Using an Existence Check
389 The following example uses the open() function to try to create the
390 LOCKFILE file and open it for writing. Since the open() function speci‐
391 fies the O_EXCL flag, the call fails if the file already exists. In
392 that case, the program assumes that someone else is updating the pass‐
393 word file and exits.
394
395
396 #include <fcntl.h>
397 #include <stdio.h>
398 #include <stdlib.h>
399
400 #define LOCKFILE "/etc/ptmp"
401 ...
402 int pfd; /* Integer for file descriptor returned by open() call. */
403 ...
404 if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
405 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
406 {
407 fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
408 exit(1);
409 }
410 ...
411
412 Opening a File for Writing
413 The following example opens a file for writing, creating the file if it
414 does not already exist. If the file does exist, the system truncates
415 the file to zero bytes.
416
417
418 #include <fcntl.h>
419 #include <stdio.h>
420 #include <stdlib.h>
421
422 #define LOCKFILE "/etc/ptmp"
423 ...
424 int pfd;
425 char pathname[PATH_MAX+1];
426 ...
427 if ((pfd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC,
428 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
429 {
430 perror("Cannot open output file\n"); exit(1);
431 }
432 ...
433
435 POSIX.1‐2008 does not require that terminal parameters be automatically
436 set to any state on first open, nor that they be reset after the last
437 close. It is possible for a non-conforming application to leave a ter‐
438 minal device in a state where the next process to use that device finds
439 it in a non-conforming state, but has no way of determining this. To
440 ensure that the device is set to a conforming initial state, applica‐
441 tions which perform a first open of a terminal (other than a pseudo-
442 terminal) should do so using the O_TTY_INIT flag to set the parameters
443 associated with the terminal to a conforming state.
444
445 Except as specified in this volume of POSIX.1‐2017, the flags allowed
446 in oflag are not mutually-exclusive and any number of them may be used
447 simultaneously. Not all combinations of flags make sense. For example,
448 using O_SEARCH | O_CREAT will successfully open a pre-existing direc‐
449 tory for searching, but if there is no existing file by that name, then
450 it is unspecified whether a regular file will be created. Likewise, if
451 a non-directory file descriptor is successfully returned, it is unspec‐
452 ified whether that descriptor will have execute permissions as if by
453 O_EXEC (note that it is unspecified whether O_EXEC and O_SEARCH have
454 the same value).
455
457 Some implementations permit opening FIFOs with O_RDWR. Since FIFOs
458 could be implemented in other ways, and since two file descriptors can
459 be used to the same effect, this possibility is left as undefined.
460
461 See getgroups() about the group of a newly created file.
462
463 The use of open() to create a regular file is preferable to the use of
464 creat(), because the latter is redundant and included only for histori‐
465 cal reasons.
466
467 The use of the O_TRUNC flag on FIFOs and directories (pipes cannot be
468 open()-ed) must be permissible without unexpected side-effects (for
469 example, creat() on a FIFO must not remove data). Since terminal spe‐
470 cial files might have type-ahead data stored in the buffer, O_TRUNC
471 should not affect their content, particularly if a program that nor‐
472 mally opens a regular file should open the current controlling terminal
473 instead. Other file types, particularly implementation-defined ones,
474 are left implementation-defined.
475
476 POSIX.1‐2008 permits [EACCES] to be returned for conditions other than
477 those explicitly listed.
478
479 The O_NOCTTY flag was added to allow applications to avoid unintention‐
480 ally acquiring a controlling terminal as a side-effect of opening a
481 terminal file. This volume of POSIX.1‐2017 does not specify how a con‐
482 trolling terminal is acquired, but it allows an implementation to pro‐
483 vide this on open() if the O_NOCTTY flag is not set and other condi‐
484 tions specified in the Base Definitions volume of POSIX.1‐2017, Chapter
485 11, General Terminal Interface are met.
486
487 In historical implementations the value of O_RDONLY is zero. Because of
488 that, it is not possible to detect the presence of O_RDONLY and another
489 option. Future implementations should encode O_RDONLY and O_WRONLY as
490 bit flags so that:
491
492
493 O_RDONLY | O_WRONLY == O_RDWR
494
495 O_EXEC and O_SEARCH are specified as two of the five file access modes.
496 Since O_EXEC does not apply to directories, and O_SEARCH only applies
497 to directories, their values need not be distinct. Since O_RDONLY has
498 historically had the value zero, implementations are not able to dis‐
499 tinguish between O_SEARCH and O_SEARCH | O_RDONLY, and similarly for
500 O_EXEC.
501
502 In general, the open() function follows the symbolic link if path names
503 a symbolic link. However, the open() function, when called with O_CREAT
504 and O_EXCL, is required to fail with [EEXIST] if path names an existing
505 symbolic link, even if the symbolic link refers to a nonexistent file.
506 This behavior is required so that privileged applications can create a
507 new file in a known location without the possibility that a symbolic
508 link might cause the file to be created in a different location.
509
510 For example, a privileged application that must create a file with a
511 predictable name in a user-writable directory, such as the user's home
512 directory, could be compromised if the user creates a symbolic link
513 with that name that refers to a nonexistent file in a system directory.
514 If the user can influence the contents of a file, the user could com‐
515 promise the system by creating a new system configuration or spool file
516 that would then be interpreted by the system. The test for a symbolic
517 link which refers to a nonexisting file must be atomic with the cre‐
518 ation of a new file.
519
520 In addition, the open() function refuses to open non-directories if the
521 O_DIRECTORY flag is set. This avoids race conditions whereby a user
522 might compromise the system by substituting a hard link to a sensitive
523 file (e.g., a device or a FIFO) while a privileged application is run‐
524 ning, where opening a file even for read access might have undesirable
525 side-effects.
526
527 In addition, the open() function does not follow symbolic links if the
528 O_NOFOLLOW flag is set. This avoids race conditions whereby a user
529 might compromise the system by substituting a symbolic link to a sensi‐
530 tive file (e.g., a device) while a privileged application is running,
531 where opening a file even for read access might have undesirable side-
532 effects.
533
534 The POSIX.1‐1990 standard required that the group ID of a newly created
535 file be set to the group ID of its parent directory or to the effective
536 group ID of the creating process. FIPS 151‐2 required that implementa‐
537 tions provide a way to have the group ID be set to the group ID of the
538 containing directory, but did not prohibit implementations also sup‐
539 porting a way to set the group ID to the effective group ID of the cre‐
540 ating process. Conforming applications should not assume which group
541 ID will be used. If it matters, an application can use chown() to set
542 the group ID after the file is created, or determine under what condi‐
543 tions the implementation will set the desired group ID.
544
545 The purpose of the openat() function is to enable opening files in
546 directories other than the current working directory without exposure
547 to race conditions. Any part of the path of a file could be changed in
548 parallel to a call to open(), resulting in unspecified behavior. By
549 opening a file descriptor for the target directory and using the ope‐
550 nat() function it can be guaranteed that the opened file is located
551 relative to the desired directory. Some implementations use the ope‐
552 nat() function for other purposes as well. In some cases, if the oflag
553 parameter has the O_XATTR bit set, the returned file descriptor pro‐
554 vides access to extended attributes. This functionality is not stan‐
555 dardized here.
556
558 None.
559
561 chmod(), close(), creat(), dirfd(), dup(), exec, fcntl(), fdopendir(),
562 link(), lseek(), mkdtemp(), mknod(), read(), symlink(), umask(),
563 unlockpt(), write()
564
565 The Base Definitions volume of POSIX.1‐2017, Chapter 11, General Termi‐
566 nal Interface, <fcntl.h>, <sys_stat.h>, <sys_types.h>
567
569 Portions of this text are reprinted and reproduced in electronic form
570 from IEEE Std 1003.1-2017, Standard for Information Technology -- Por‐
571 table Operating System Interface (POSIX), The Open Group Base Specifi‐
572 cations Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of
573 Electrical and Electronics Engineers, Inc and The Open Group. In the
574 event of any discrepancy between this version and the original IEEE and
575 The Open Group Standard, the original IEEE and The Open Group Standard
576 is the referee document. The original Standard can be obtained online
577 at http://www.opengroup.org/unix/online.html .
578
579 Any typographical or formatting errors that appear in this page are
580 most likely to have been introduced during the conversion of the source
581 files to man page format. To report such errors, see https://www.ker‐
582 nel.org/doc/man-pages/reporting_bugs.html .
583
584
585
586IEEE/The Open Group 2017 OPEN(3P)