POSIX:fcntl
lastmod 2024-07-09created 2016-12-0510 edits
Syntax
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
open
- open(2) - Linux manual page
- open(3): open file - Linux man page
- 2013.08.29_UNIX Programming_Chapter 3_File I/O — KKIMSSI
- O_NOCTTY - open : Naver Blog
Flags
| Open option | Description |
| O_RDONLY | Open read-only |
| O_WRONLY | Open write-only |
| O_RDWR | Both reading and writing are allowed |
| O_CREAT | Creates the file if it does not exist. |
| O_EXCL | When |
| O_TRUNC | Deletes all existing contents of the file. |
| O_APPEND | After open, the write pointer is placed at the end of the file so that writes append to the file. |
| O_NOCITTY | If the target being opened is a terminal, the terminal is not assigned as the program's controlling terminal. (It prevents it from becoming the controlling TTY so that the program is not terminated when a CTRL-C character arrives during data transfer.) |
| O_NONBLOCK | When there is nothing to read, returns immediately instead of waiting until there is something to read. |
| O_SYNC | When writing, waits until the actual write is complete. In other words, it returns only after the write has physically completed. |
O_NONBLOCK
- In BLOCK mode
- When writing - waits until another thread reads the file with read.
- When reading - waits until another thread writes to the file with write.
- In NON BLOCK mode
- When writing - if no other thread is waiting in a read state, it ends without delay by returning an error.
- When reading - if there is something to read, it returns the number of bytes read; otherwise it returns -1. Either way it ends immediately without delay.
Let's take serial communication as an example. Without the O_NONBLOCK option:
If you read() data this way, the program stays blocked until data arrives. It is easiest to think of the program as stopped. In the case of write(), it waits until the other side enters read().
With the O_NONBLOCK option:
It returns without waiting, whether or not there is data. If there is data to read, it writes the data read into buf and returns the number of bytes read in res. If not, it returns -1 in res. write() also behaves the same way as read().
fcntl
manipulate file descriptor.
PIPE_BUF
See Named pipe#PIPE_BUF for details.
See also
Favorite site
- open(2) - Linux manual page
- fcntl(2) - Linux manual page
- open: opening a file
- fopen() and open() ?
- What is the biggest difference between open and fopen? - On Linux
- Chapter 1. open(2)
- File control using fcntl