1OPEN(2) Linux Programmer's Manual OPEN(2)
2
3
4
6 open, creat - open and possibly create a file or device
7
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12
13 int open(const char *pathname, int flags);
14 int open(const char *pathname, int flags, mode_t mode);
15
16 int creat(const char *pathname, mode_t mode);
17
19 Given a pathname for a file, open() returns a file descriptor, a small,
20 nonnegative integer for use in subsequent system calls (read(2),
21 write(2), lseek(2), fcntl(2), etc.). The file descriptor returned by a
22 successful call will be the lowest-numbered file descriptor not cur‐
23 rently open for the process.
24
25 By default, the new file descriptor is set to remain open across an
26 execve(2) (i.e., the FD_CLOEXEC file descriptor flag described in
27 fcntl(2) is initially disabled; the O_CLOEXEC flag, described below,
28 can be used to change this default). The file offset is set to the
29 beginning of the file (see lseek(2)).
30
31 A call to open() creates a new open file description, an entry in the
32 system-wide table of open files. This entry records the file offset
33 and the file status flags (modifiable via the fcntl(2) F_SETFL opera‐
34 tion). A file descriptor is a reference to one of these entries; this
35 reference is unaffected if pathname is subsequently removed or modified
36 to refer to a different file. The new open file description is ini‐
37 tially not shared with any other process, but sharing may arise via
38 fork(2).
39
40 The argument flags must include one of the following access modes:
41 O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-
42 only, write-only, or read/write, respectively.
43
44 In addition, zero or more file creation flags and file status flags can
45 be bitwise-or'd in flags. The file creation flags are O_CLOEXEC,
46 O_CREAT, O_DIRECTORY, O_EXCL, O_NOCTTY, O_NOFOLLOW, O_TRUNC, and
47 O_TTY_INIT. The file status flags are all of the remaining flags
48 listed below. The distinction between these two groups of flags is
49 that the file status flags can be retrieved and (in some cases) modi‐
50 fied using fcntl(2). The full list of file creation flags and file
51 status flags is as follows:
52
53 O_APPEND
54 The file is opened in append mode. Before each write(2), the
55 file offset is positioned at the end of the file, as if with
56 lseek(2). O_APPEND may lead to corrupted files on NFS file sys‐
57 tems if more than one process appends data to a file at once.
58 This is because NFS does not support appending to a file, so the
59 client kernel has to simulate it, which can't be done without a
60 race condition.
61
62 O_ASYNC
63 Enable signal-driven I/O: generate a signal (SIGIO by default,
64 but this can be changed via fcntl(2)) when input or output
65 becomes possible on this file descriptor. This feature is
66 available only for terminals, pseudoterminals, sockets, and
67 (since Linux 2.6) pipes and FIFOs. See fcntl(2) for further
68 details.
69
70 O_CLOEXEC (Since Linux 2.6.23)
71 Enable the close-on-exec flag for the new file descriptor.
72 Specifying this flag permits a program to avoid additional
73 fcntl(2) F_SETFD operations to set the FD_CLOEXEC flag. Addi‐
74 tionally, use of this flag is essential in some multithreaded
75 programs since using a separate fcntl(2) F_SETFD operation to
76 set the FD_CLOEXEC flag does not suffice to avoid race condi‐
77 tions where one thread opens a file descriptor at the same time
78 as another thread does a fork(2) plus execve(2).
79
80 O_CREAT
81 If the file does not exist it will be created. The owner (user
82 ID) of the file is set to the effective user ID of the process.
83 The group ownership (group ID) is set either to the effective
84 group ID of the process or to the group ID of the parent direc‐
85 tory (depending on file system type and mount options, and the
86 mode of the parent directory, see the mount options bsdgroups
87 and sysvgroups described in mount(8)).
88
89 mode specifies the permissions to use in case a new file is cre‐
90 ated. This argument must be supplied when O_CREAT is specified
91 in flags; if O_CREAT is not specified, then mode is ignored.
92 The effective permissions are modified by the process's umask in
93 the usual way: The permissions of the created file are
94 (mode & ~umask). Note that this mode applies only to future
95 accesses of the newly created file; the open() call that creates
96 a read-only file may well return a read/write file descriptor.
97
98 The following symbolic constants are provided for mode:
99
100 S_IRWXU 00700 user (file owner) has read, write and execute
101 permission
102
103 S_IRUSR 00400 user has read permission
104
105 S_IWUSR 00200 user has write permission
106
107 S_IXUSR 00100 user has execute permission
108
109 S_IRWXG 00070 group has read, write and execute permission
110
111 S_IRGRP 00040 group has read permission
112
113 S_IWGRP 00020 group has write permission
114
115 S_IXGRP 00010 group has execute permission
116
117 S_IRWXO 00007 others have read, write and execute permission
118
119 S_IROTH 00004 others have read permission
120
121 S_IWOTH 00002 others have write permission
122
123 S_IXOTH 00001 others have execute permission
124
125 O_DIRECT (Since Linux 2.4.10)
126 Try to minimize cache effects of the I/O to and from this file.
127 In general this will degrade performance, but it is useful in
128 special situations, such as when applications do their own
129 caching. File I/O is done directly to/from user-space buffers.
130 The O_DIRECT flag on its own makes an effort to transfer data
131 synchronously, but does not give the guarantees of the O_SYNC
132 flag that data and necessary metadata are transferred. To guar‐
133 antee synchronous I/O, O_SYNC must be used in addition to
134 O_DIRECT. See NOTES below for further discussion.
135
136 A semantically similar (but deprecated) interface for block
137 devices is described in raw(8).
138
139 O_DIRECTORY
140 If pathname is not a directory, cause the open to fail. This
141 flag is Linux-specific, and was added in kernel version 2.1.126,
142 to avoid denial-of-service problems if opendir(3) is called on a
143 FIFO or tape device.
144
145 O_EXCL Ensure that this call creates the file: if this flag is speci‐
146 fied in conjunction with O_CREAT, and pathname already exists,
147 then open() will fail.
148
149 When these two flags are specified, symbolic links are not fol‐
150 lowed: if pathname is a symbolic link, then open() fails regard‐
151 less of where the symbolic link points to.
152
153 In general, the behavior of O_EXCL is undefined if it is used
154 without O_CREAT. There is one exception: on Linux 2.6 and
155 later, O_EXCL can be used without O_CREAT if pathname refers to
156 a block device. If the block device is in use by the system
157 (e.g., mounted), open() fails with the error EBUSY.
158
159 On NFS, O_EXCL is supported only when using NFSv3 or later on
160 kernel 2.6 or later. In NFS environments where O_EXCL support
161 is not provided, programs that rely on it for performing locking
162 tasks will contain a race condition. Portable programs that
163 want to perform atomic file locking using a lockfile, and need
164 to avoid reliance on NFS support for O_EXCL, can create a unique
165 file on the same file system (e.g., incorporating hostname and
166 PID), and use link(2) to make a link to the lockfile. If
167 link(2) returns 0, the lock is successful. Otherwise, use
168 stat(2) on the unique file to check if its link count has
169 increased to 2, in which case the lock is also successful.
170
171 O_LARGEFILE
172 (LFS) Allow files whose sizes cannot be represented in an off_t
173 (but can be represented in an off64_t) to be opened. The
174 _LARGEFILE64_SOURCE macro must be defined (before including any
175 header files) in order to obtain this definition. Setting the
176 _FILE_OFFSET_BITS feature test macro to 64 (rather than using
177 O_LARGEFILE) is the preferred method of accessing large files on
178 32-bit systems (see feature_test_macros(7)).
179
180 O_NOATIME (Since Linux 2.6.8)
181 Do not update the file last access time (st_atime in the inode)
182 when the file is read(2). This flag is intended for use by
183 indexing or backup programs, where its use can significantly
184 reduce the amount of disk activity. This flag may not be effec‐
185 tive on all file systems. One example is NFS, where the server
186 maintains the access time.
187
188 O_NOCTTY
189 If pathname refers to a terminal device—see tty(4)—it will not
190 become the process's controlling terminal even if the process
191 does not have one.
192
193 O_NOFOLLOW
194 If pathname is a symbolic link, then the open fails. This is a
195 FreeBSD extension, which was added to Linux in version 2.1.126.
196 Symbolic links in earlier components of the pathname will still
197 be followed. See also O_NOPATH below.
198
199 O_NONBLOCK or O_NDELAY
200 When possible, the file is opened in nonblocking mode. Neither
201 the open() nor any subsequent operations on the file descriptor
202 which is returned will cause the calling process to wait. For
203 the handling of FIFOs (named pipes), see also fifo(7). For a
204 discussion of the effect of O_NONBLOCK in conjunction with
205 mandatory file locks and with file leases, see fcntl(2).
206
207 O_PATH (since Linux 2.6.39)
208 Obtain a file descriptor that can be used for two purposes: to
209 indicate a location in the file-system tree and to perform oper‐
210 ations that act purely at the file descriptor level. The file
211 itself is not opened, and other file operations (e.g., read(2),
212 write(2), fchmod(2), fchown(2), fgetxattr(2)) fail with the
213 error EBADF.
214
215 The following operations can be performed on the resulting file
216 descriptor:
217
218 * close(2); fchdir(2) (since Linux 3.5); fstat(2) (since Linux
219 3.6).
220
221 * Duplicating the file descriptor (dup(2), fcntl(2) F_DUPFD,
222 etc.).
223
224 * Getting and setting file descriptor flags (fcntl(2) F_GETFD
225 and F_SETFD).
226
227 * Retrieving open file status flags using the fcntl(2) F_GETFL
228 operation: the returned flags will include the bit O_PATH.
229
230
231 * Passing the file descriptor as the dirfd argument of ope‐
232 nat(2) and the other "*at()" system calls.
233
234 * Passing the file descriptor to another process via a UNIX
235 domain socket (see SCM_RIGHTS in unix(7)).
236
237 When O_PATH is specified in flags, flag bits other than O_DIREC‐
238 TORY and O_NOFOLLOW are ignored.
239
240 If the O_NOFOLLOW flag is also specified, then the call returns
241 a file descriptor referring to the symbolic link. This file
242 descriptor can be used as the dirfd argument in calls to fchow‐
243 nat(2), fstatat(2), linkat(2), and readlinkat(2) with an empty
244 pathname to have the calls operate on the symbolic link.
245
246 O_SYNC The file is opened for synchronous I/O. Any write(2)s on the
247 resulting file descriptor will block the calling process until
248 the data has been physically written to the underlying hardware.
249 But see NOTES below.
250
251 O_TRUNC
252 If the file already exists and is a regular file and the open
253 mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be
254 truncated to length 0. If the file is a FIFO or terminal device
255 file, the O_TRUNC flag is ignored. Otherwise the effect of
256 O_TRUNC is unspecified.
257
258 Some of these optional flags can be altered using fcntl(2) after the
259 file has been opened.
260
261 creat() is equivalent to open() with flags equal to
262 O_CREAT|O_WRONLY|O_TRUNC.
263
265 open() and creat() return the new file descriptor, or -1 if an error
266 occurred (in which case, errno is set appropriately).
267
269 EACCES The requested access to the file is not allowed, or search per‐
270 mission is denied for one of the directories in the path prefix
271 of pathname, or the file did not exist yet and write access to
272 the parent directory is not allowed. (See also path_resolu‐
273 tion(7).)
274
275 EDQUOT Where O_CREAT is specified, the file does not exist, and the
276 user's quota of disk blocks or inodes on the file system has
277 been exhausted.
278
279 EEXIST pathname already exists and O_CREAT and O_EXCL were used.
280
281 EFAULT pathname points outside your accessible address space.
282
283 EFBIG See EOVERFLOW.
284
285 EINTR While blocked waiting to complete an open of a slow device
286 (e.g., a FIFO; see fifo(7)), the call was interrupted by a sig‐
287 nal handler; see signal(7).
288
289 EISDIR pathname refers to a directory and the access requested involved
290 writing (that is, O_WRONLY or O_RDWR is set).
291
292 ELOOP Too many symbolic links were encountered in resolving pathname,
293 or O_NOFOLLOW was specified but pathname was a symbolic link.
294
295 EMFILE The process already has the maximum number of files open.
296
297 ENAMETOOLONG
298 pathname was too long.
299
300 ENFILE The system limit on the total number of open files has been
301 reached.
302
303 ENODEV pathname refers to a device special file and no corresponding
304 device exists. (This is a Linux kernel bug; in this situation
305 ENXIO must be returned.)
306
307 ENOENT O_CREAT is not set and the named file does not exist. Or, a
308 directory component in pathname does not exist or is a dangling
309 symbolic link.
310
311 ENOMEM Insufficient kernel memory was available.
312
313 ENOSPC pathname was to be created but the device containing pathname
314 has no room for the new file.
315
316 ENOTDIR
317 A component used as a directory in pathname is not, in fact, a
318 directory, or O_DIRECTORY was specified and pathname was not a
319 directory.
320
321 ENXIO O_NONBLOCK | O_WRONLY is set, the named file is a FIFO and no
322 process has the file open for reading. Or, the file is a device
323 special file and no corresponding device exists.
324
325 EOVERFLOW
326 pathname refers to a regular file that is too large to be
327 opened. The usual scenario here is that an application compiled
328 on a 32-bit platform without -D_FILE_OFFSET_BITS=64 tried to
329 open a file whose size exceeds (2<<31)-1 bits; see also O_LARGE‐
330 FILE above. This is the error specified by POSIX.1-2001; in
331 kernels before 2.6.24, Linux gave the error EFBIG for this case.
332
333 EPERM The O_NOATIME flag was specified, but the effective user ID of
334 the caller did not match the owner of the file and the caller
335 was not privileged (CAP_FOWNER).
336
337 EROFS pathname refers to a file on a read-only file system and write
338 access was requested.
339
340 ETXTBSY
341 pathname refers to an executable image which is currently being
342 executed and write access was requested.
343
344 EWOULDBLOCK
345 The O_NONBLOCK flag was specified, and an incompatible lease was
346 held on the file (see fcntl(2)).
347
349 SVr4, 4.3BSD, POSIX.1-2001. The O_DIRECTORY, O_NOATIME, O_NOFOLLOW,
350 and O_PATH flags are Linux-specific, and one may need to define
351 _GNU_SOURCE (before including any header files) to obtain their defini‐
352 tions.
353
354 The O_CLOEXEC flag is not specified in POSIX.1-2001, but is specified
355 in POSIX.1-2008.
356
357 O_DIRECT is not specified in POSIX; one has to define _GNU_SOURCE
358 (before including any header files) to get its definition.
359
361 Under Linux, the O_NONBLOCK flag indicates that one wants to open but
362 does not necessarily have the intention to read or write. This is typ‐
363 ically used to open devices in order to get a file descriptor for use
364 with ioctl(2).
365
366 Unlike the other values that can be specified in flags, the access mode
367 values O_RDONLY, O_WRONLY, and O_RDWR, do not specify individual bits.
368 Rather, they define the low order two bits of flags, and are defined
369 respectively as 0, 1, and 2. In other words, the combination O_RDONLY
370 | O_WRONLY is a logical error, and certainly does not have the same
371 meaning as O_RDWR. Linux reserves the special, nonstandard access mode
372 3 (binary 11) in flags to mean: check for read and write permission on
373 the file and return a descriptor that can't be used for reading or
374 writing. This nonstandard access mode is used by some Linux drivers to
375 return a descriptor that is to be used only for device-specific
376 ioctl(2) operations.
377
378 The (undefined) effect of O_RDONLY | O_TRUNC varies among implementa‐
379 tions. On many systems the file is actually truncated.
380
381 There are many infelicities in the protocol underlying NFS, affecting
382 amongst others O_SYNC and O_NDELAY.
383
384 POSIX provides for three different variants of synchronized I/O, corre‐
385 sponding to the flags O_SYNC, O_DSYNC, and O_RSYNC. Currently
386 (2.6.31), Linux implements only O_SYNC, but glibc maps O_DSYNC and
387 O_RSYNC to the same numerical value as O_SYNC. Most Linux file systems
388 don't actually implement the POSIX O_SYNC semantics, which require all
389 metadata updates of a write to be on disk on returning to user space,
390 but only the O_DSYNC semantics, which require only actual file data and
391 metadata necessary to retrieve it to be on disk by the time the system
392 call returns.
393
394 Note that open() can open device special files, but creat() cannot cre‐
395 ate them; use mknod(2) instead.
396
397 On NFS file systems with UID mapping enabled, open() may return a file
398 descriptor but, for example, read(2) requests are denied with EACCES.
399 This is because the client performs open() by checking the permissions,
400 but UID mapping is performed by the server upon read and write
401 requests.
402
403 If the file is newly created, its st_atime, st_ctime, st_mtime fields
404 (respectively, time of last access, time of last status change, and
405 time of last modification; see stat(2)) are set to the current time,
406 and so are the st_ctime and st_mtime fields of the parent directory.
407 Otherwise, if the file is modified because of the O_TRUNC flag, its
408 st_ctime and st_mtime fields are set to the current time.
409
410 O_DIRECT
411 The O_DIRECT flag may impose alignment restrictions on the length and
412 address of user-space buffers and the file offset of I/Os. In Linux
413 alignment restrictions vary by file system and kernel version and might
414 be absent entirely. However there is currently no file system-indepen‐
415 dent interface for an application to discover these restrictions for a
416 given file or file system. Some file systems provide their own inter‐
417 faces for doing so, for example the XFS_IOC_DIOINFO operation in
418 xfsctl(3).
419
420 Under Linux 2.4, transfer sizes, and the alignment of the user buffer
421 and the file offset must all be multiples of the logical block size of
422 the file system. Under Linux 2.6, alignment to 512-byte boundaries
423 suffices.
424
425 O_DIRECT I/Os should never be run concurrently with the fork(2) system
426 call, if the memory buffer is a private mapping (i.e., any mapping cre‐
427 ated with the mmap(2) MAP_PRIVATE flag; this includes memory allocated
428 on the heap and statically allocated buffers). Any such I/Os, whether
429 submitted via an asynchronous I/O interface or from another thread in
430 the process, should be completed before fork(2) is called. Failure to
431 do so can result in data corruption and undefined behavior in parent
432 and child processes. This restriction does not apply when the memory
433 buffer for the O_DIRECT I/Os was created using shmat(2) or mmap(2) with
434 the MAP_SHARED flag. Nor does this restriction apply when the memory
435 buffer has been advised as MADV_DONTFORK with madvise(2), ensuring that
436 it will not be available to the child after fork(2).
437
438 The O_DIRECT flag was introduced in SGI IRIX, where it has alignment
439 restrictions similar to those of Linux 2.4. IRIX has also a fcntl(2)
440 call to query appropriate alignments, and sizes. FreeBSD 4.x intro‐
441 duced a flag of the same name, but without alignment restrictions.
442
443 O_DIRECT support was added under Linux in kernel version 2.4.10. Older
444 Linux kernels simply ignore this flag. Some file systems may not
445 implement the flag and open() will fail with EINVAL if it is used.
446
447 Applications should avoid mixing O_DIRECT and normal I/O to the same
448 file, and especially to overlapping byte regions in the same file.
449 Even when the file system correctly handles the coherency issues in
450 this situation, overall I/O throughput is likely to be slower than
451 using either mode alone. Likewise, applications should avoid mixing
452 mmap(2) of files with direct I/O to the same files.
453
454 The behaviour of O_DIRECT with NFS will differ from local file systems.
455 Older kernels, or kernels configured in certain ways, may not support
456 this combination. The NFS protocol does not support passing the flag
457 to the server, so O_DIRECT I/O will bypass the page cache only on the
458 client; the server may still cache the I/O. The client asks the server
459 to make the I/O synchronous to preserve the synchronous semantics of
460 O_DIRECT. Some servers will perform poorly under these circumstances,
461 especially if the I/O size is small. Some servers may also be config‐
462 ured to lie to clients about the I/O having reached stable storage;
463 this will avoid the performance penalty at some risk to data integrity
464 in the event of server power failure. The Linux NFS client places no
465 alignment restrictions on O_DIRECT I/O.
466
467 In summary, O_DIRECT is a potentially powerful tool that should be used
468 with caution. It is recommended that applications treat use of
469 O_DIRECT as a performance option which is disabled by default.
470
471 "The thing that has always disturbed me about O_DIRECT is that
472 the whole interface is just stupid, and was probably designed by
473 a deranged monkey on some serious mind-controlling sub‐
474 stances."—Linus
475
477 Currently, it is not possible to enable signal-driven I/O by specifying
478 O_ASYNC when calling open(); use fcntl(2) to enable this flag.
479
481 chmod(2), chown(2), close(2), dup(2), fcntl(2), link(2), lseek(2),
482 mknod(2), mmap(2), mount(2), openat(2), read(2), socket(2), stat(2),
483 umask(2), unlink(2), write(2), fopen(3), fifo(7), path_resolution(7),
484 symlink(7)
485
487 This page is part of release 3.53 of the Linux man-pages project. A
488 description of the project, and information about reporting bugs, can
489 be found at http://www.kernel.org/doc/man-pages/.
490
491
492
493Linux 2013-07-21 OPEN(2)