Skip to content
systemcoding.dev
Systems Programming

Read the file status flags with fcntl F_GETFL

Read an open descriptor's access mode and status flags such as O_APPEND and O_NONBLOCK with fcntl F_GETFL on Linux 6.12, masking with O_ACCMODE.

2 min read
Summarize in AI

fcntl(fd, F_GETFL) returns the flags of an open file description: the access mode, plus status flags such as O_APPEND, O_NONBLOCK and O_SYNC. Creation flags like O_CREAT and O_TRUNC are not kept, so you cannot read them back. The access mode is not a bit flag, so testing flags & O_RDONLY is a bug: O_RDONLY is 0 on Linux. You mask with O_ACCMODE and compare, as in POSIX fcntl.

getfl.cc
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(void) {
    int fd = open("log.txt", O_RDWR | O_CREAT | O_APPEND, 0644);
    int fl = fcntl(fd, F_GETFL);

    const char *mode = (fl & O_ACCMODE) == O_RDONLY ? "read-only"
                     : (fl & O_ACCMODE) == O_WRONLY ? "write-only" : "read-write";
    printf("access: %s\n", mode);
    printf("append: %s\n", (fl & O_APPEND) ? "yes" : "no");
    printf("nonblock: %s\n", (fl & O_NONBLOCK) ? "yes" : "no");
    return 0;
}
Text
access: read-write
append: yes
nonblock: no

The flags live on the open file description, so every descriptor made by dup or inherited by fork shows the same answer. Changing one with F_SETFL changes it for all of them, which is how a child's O_NONBLOCK can unexpectedly affect the parent's reads.

F_SETFL can change only a few flags (O_APPEND, O_NONBLOCK, O_ASYNC, O_DIRECT, O_NOATIME) on Linux 6.12. The access mode and O_SYNC are fixed at open. The usual pattern is get, OR in the bit, set.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.