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