Skip to content
Visual explainer 3h to learn 5 steps

lseek, dup2, fcntl & open flags

Reposition, duplicate and reconfigure descriptors to implement redirection.

By Invicly Tech, , in Linux System Programming. About 13 minutes to read.

Topic 10 of 42

In short

Beyond read and write, a few calls give you full control over descriptors. lseek moves the file offset, dup2 makes one descriptor number refer to another open file, which is exactly how shells redirect output, and fcntl reads or changes descriptor flags such as O_NONBLOCK and FD_CLOEXEC.

Explained simply

Every open file has a position, called the offset. read and write start there and move it forward. lseek moves it anywhere you like, like moving a bookmark. You can even move past the end of the file. If you then write, the gap becomes a hole that reads back as zeros but uses no disk space. A file with holes is called a sparse file.

Descriptors can be copied. dup2(old, new) makes the number new refer to the same open file as old. That one call is the whole trick behind the shell's > and 2>&1.

fcntl is a toolbox for a descriptor you already have. It can switch on non-blocking mode, mark the descriptor to close automatically when you exec another program, and lock parts of a file.

When write returns, your data is usually only in the kernel's memory. A power cut a second later could lose it. fsync waits until the data is really on the disk. Databases and anything that must not lose data rely on it.

Press Play on a diagram to walk through it one step at a time.

FlowHow a shell runs cmd > out.txt
  1. 1
    fork

    Child gets a copy of the descriptor table.

  2. 2
    open

    Child opens out.txt and gets fd 3.

  3. 3
    dup2(3, 1)

    fd 1 now refers to out.txt.

  4. 4
    close(3)

    Drop the extra descriptor.

  5. 5
    exec

    The new program writes to fd 1, unaware of the redirect.

FlowReplace a config file safely
  1. Step 1
    Write config.tmp

    Open with O_CREAT | O_EXCL, write everything

  2. Step 2
    fsync the temp file

    Its data is now on disk

  3. Step 3
    rename to config

    Atomic: readers see old or new, never half

  4. Step 4
    fsync the directory

    The new name itself survives a crash

MapWhat fcntl can do
fcntl(fd, cmd, ...)
  • Duplicate
    • F_DUPFD
    • F_DUPFD_CLOEXEC
  • Descriptor flags
    • F_GETFD
    • F_SETFD with FD_CLOEXEC
  • File status flags
    • F_GETFL
    • F_SETFL with O_NONBLOCK or O_APPEND
  • Record locks
    • F_SETLK
    • F_SETLKW
    • F_GETLK
    • F_OFD_SETLK (Linux)
  • Pipe size (Linux)
    • F_GETPIPE_SZ
    • F_SETPIPE_SZ

In depth

lseek, holes and sparse files

lseek(fd, offset, whence) sets the offset relative to the start (SEEK_SET), the current position (SEEK_CUR) or the end of the file (SEEK_END), and returns the new position. So lseek(fd, 0, SEEK_CUR) tells you where you are, and lseek(fd, 0, SEEK_END) gives the size. On pipes, sockets and terminals it fails with ESPIPE, because they have no positions.

Seeking past the end and writing leaves a hole. The file's size includes the hole, but no blocks are allocated for it, so ls -l and du disagree. Virtual machine disk images and database files use this all the time. SEEK_DATA and SEEK_HOLE let a program find where the real data is, and GNU cp detects holes by default.

pread and pwrite read or write at a given offset without moving the shared offset. Several threads can use them on one descriptor without stepping on each other.

  • ls -l shows the logical size; du shows blocks really used
  • truncate -s 10G disk.img makes a sparse file instantly
  • On 32-bit builds, compile with -D_FILE_OFFSET_BITS=64 for large files

dup, dup2 and the order of redirections

dup(fd) returns the lowest free number as a copy of fd. dup2(old, new) uses exactly the number you choose: if new is already open, it is closed first, and both steps happen atomically. If old equals new, dup2 does nothing and returns new.

Shells apply redirections from left to right, and this explains a classic puzzle. In cmd > out 2>&1, fd 1 is pointed at out first, then fd 2 becomes a copy of fd 1, so both go to the file. In cmd 2>&1 > out, fd 2 copies fd 1 while it is still the terminal, and only then is fd 1 pointed at out, so errors still reach the screen.

To redirect temporarily inside one program, save the original first with saved = dup(1), redirect, and later restore it with dup2(saved, 1) and close(saved).

CompareOrder matters: two redirections
cmd > out 2>&1
  • open out, dup2 it onto fd 1
  • dup2(1, 2): fd 2 now also points to out
  • Output and errors both go to the file
cmd 2>&1 > out
  • dup2(1, 2): fd 2 points to the terminal
  • open out, dup2 it onto fd 1
  • Errors still appear on the terminal

fcntl: descriptor flags and file status flags

fcntl manages two different sets of flags, and mixing them up causes bugs. F_GETFD and F_SETFD handle descriptor flags. There is really only one: FD_CLOEXEC. It belongs to that single descriptor number, so a dup copy does not have it.

F_GETFL and F_SETFL handle file status flags such as O_APPEND and O_NONBLOCK. These live in the shared open file description, so they affect every copy made by dup or fork. Setting O_NONBLOCK on a terminal that your shell also uses can confuse the shell after your program exits.

Always read, change, then write back: fl = fcntl(fd, F_GETFL), then fcntl(fd, F_SETFL, fl | O_NONBLOCK). Setting FD_CLOEXEC after open leaves a short window in which another thread could fork and exec and leak the descriptor. Ask for it at creation instead: O_CLOEXEC, pipe2 with O_CLOEXEC, accept4 with SOCK_CLOEXEC, or F_DUPFD_CLOEXEC.

O_APPEND and O_EXCL: atomic by design

Without O_APPEND, appending is two steps: seek to the end, then write. If two processes do this at the same time, both can find the same end and the second write overwrites the first. With O_APPEND, the kernel moves to the end and writes in one atomic step, so lines from several writers never overwrite each other on a local file system. Write each log line with a single write call so it stays in one piece. NFS does not guarantee this.

O_EXCL together with O_CREAT makes open fail with EEXIST if the path already exists, even if it is a symlink. The check and the creation are one atomic step, so exactly one process can win. This is the safe way to create lock files and temporary files; mkstemp uses it for you.

SequenceThe lost write without O_APPEND
Process A
log file
Process B
  1. 1lseek to end: offset 100
    Process A to log file: lseek to end: offset 100
  2. 2lseek to end: offset 100
    Process B to log file: lseek to end: offset 100
  3. 3write 20 bytes at 100
    Process A to log file: write 20 bytes at 100
  4. 4write 20 bytes at 100: A's line is overwritten
    Process B to log file: write 20 bytes at 100: A's line is overwritten

fsync, fdatasync and what durable means

A successful write puts data into the page cache. The kernel writes dirty pages to disk later, typically within about 30 seconds. fsync(fd) blocks until that file's data and metadata are on stable storage and asks the drive to flush its own cache. fdatasync skips metadata that is not needed to read the data back, such as the modification time, so it can be faster. Opening with O_SYNC or O_DSYNC makes every write behave as if followed by one of these calls.

A new file's name lives in its directory, so for full safety you also fsync the directory after creating or renaming a file. If fsync fails with EIO, do not assume a retry fixes it; the dirty pages may already be gone. Careful programs treat that as a serious error.

  • fsync: data plus metadata
  • fdatasync: data plus only the metadata needed to read it
  • sync: all file systems, mostly for admins

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Seek and create sparse files with lseek~35m
  2. 2
    Redirect output with dup2~35m
  3. 3
    Set O_NONBLOCK and FD_CLOEXEC via fcntl~35m
  4. 4
    Use O_APPEND and O_EXCL correctly~35m
  5. 5
    Make durable writes with fsync~35m

Key points

  • lseek past the end and then write to create a sparse file with a hole.
  • O_APPEND makes every write go atomically to the end, which is safe for shared logs.
  • O_CREAT | O_EXCL creates a file only if it does not already exist, atomically.
  • Open with O_CLOEXEC so descriptors do not leak into programs you exec.
  • A successful write does not mean data is on disk; call fsync for durability.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(void) {
  int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
  if (fd < 0) { perror("open"); return 1; }
  if (dup2(fd, STDOUT_FILENO) < 0) { perror("dup2"); return 1; }
  close(fd);
  execlp("ls", "ls", "-l", (char *)NULL);
  perror("execlp");
  return 1;
}

Equivalent of ls -l > out.txt; the dup2 copy does not inherit O_CLOEXEC.

Make a 1 GiB sparse file

Step 1: create a file and seek 1 GiB forward without writing anything. Step 2: write a single byte; the file's size is now 1 GiB plus one byte. Step 3: compare ls -l, which shows the logical size, with du -h, which shows the space really used, typically 4.0K for one block. Step 4: run cp sparse.img copy.img and check du again; GNU cp detects the hole and keeps the copy sparse too. The shell command truncate -s 1G file creates a similar file in one step.

c
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
  int fd = open("sparse.img", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
  if (fd < 0) { perror("open"); return 1; }
  if (lseek(fd, (off_t)1 << 30, SEEK_SET) == (off_t)-1) { perror("lseek"); return 1; }
  if (write(fd, "!", 1) != 1) { perror("write"); return 1; }
  if (close(fd) < 0) { perror("close"); return 1; }
  return 0;
}
/* ls -l sparse.img : 1073741825 bytes
   du -h sparse.img : 4.0K (only one block is really used) */

Capture output temporarily, then restore stdout

Sometimes you want one part of a program's output in a file and the rest on screen, for example to capture what a library function prints. Step 1: flush stdout and save a copy of fd 1 with dup. Step 2: open the file and dup2 it onto fd 1. Step 3: print, then flush again; otherwise the text could still be in the stdio buffer when you switch back, and land on the terminal. Step 4: dup2 the saved copy back onto fd 1 and close the spare descriptor.

c
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
  fflush(stdout);
  int saved = dup(STDOUT_FILENO);
  int fd = open("captured.txt", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
  if (saved < 0 || fd < 0) { perror("dup/open"); return 1; }
  if (dup2(fd, STDOUT_FILENO) < 0) { perror("dup2"); return 1; }
  close(fd);
  printf("this line goes to captured.txt\n");
  fflush(stdout);                          /* push it out before switching back */
  if (dup2(saved, STDOUT_FILENO) < 0) { perror("dup2"); return 1; }
  close(saved);
  printf("this line goes to the terminal\n");
  return 0;
}

Quick reference

  • lseek(fd, 0, SEEK_CUR) gives the current offset; lseek(fd, 0, SEEK_END) gives the size
  • pread and pwrite use an explicit offset and do not move the shared file offset
  • cmd > out 2>&1 sends both streams to out; cmd 2>&1 > out does not
  • fl = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, fl | O_NONBLOCK) turns on non-blocking mode
  • Prefer O_CLOEXEC, pipe2(O_CLOEXEC) and accept4(SOCK_CLOEXEC) over setting FD_CLOEXEC later
  • open(path, O_WRONLY | O_CREAT | O_EXCL, 0600) fails with EEXIST if the file already exists
  • Write a temp file, fsync it, rename it, then fsync the directory: a durable replace
  • du -h smaller than ls -lh means a sparse file; truncate -s 1G f makes one

Common mistakes

  • Forgetting to close the original descriptor after dup2.
  • Assuming write means the data survived a power loss.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does lseek return when called on a pipe?

Question 2

2Which of these belongs to one descriptor number and is not shared with dup copies?

Question 3

3Two processes append lines to one log through separate open() calls without O_APPEND. What can go wrong?

Question 4

4write() on a local file just returned success. Where is the data?

Question 5

5You run cmd 2>&1 > out.txt. Where do the error messages go?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Print the size of a file given on the command line using only open and lseek.

  2. Exercise 2medium

    Write int set_nonblock(int fd) that turns on O_NONBLOCK without clearing any other flags. Test it on the read end of an empty pipe: read should fail with EAGAIN instead of blocking.

  3. Exercise 3hard

    Make sure only one copy of your program runs: create /tmp/myapp.lock only if it does not exist, write your PID into it, and exit with a message if it already exists. Remove it when you finish.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between dup and dup2?
dup returns the lowest free descriptor number as a copy. dup2 lets you choose the number, closing it first if it is already open, which is what redirection needs.
Does O_APPEND keep whole lines together?
On a local file system, the data of each single write call is placed at the end in one piece. So write each line with one call; separate calls from different processes can still interleave between lines.
What is the difference between fsync and sync?
fsync flushes one file and waits until it is on disk. sync asks the kernel to flush all file systems, which is mostly useful for administrators; syncfs flushes the one file system that holds a given descriptor.
Why did my sparse file grow to full size after copying it?
The copying tool wrote the zeros out as real data. Use cp --sparse=always, rsync --sparse, or tar with --sparse to keep the holes.

Go deeper

ShareXLinkedInWhatsApp