Search code examples
clinuxposix

Re-open file read-only in Linux (or POSIX)


I open a file in read/write mode and do a series of reads, writes and seeks (from user input).

At some point later on I want to make the file read-only to prevent any further writes to it.

Is there a Linux (or POSIX) function to do that? Perhaps some fcntl call?

Or is my only option is to save the current position in the file, close it and reopen RD_ONLY?

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int fd = open("/path/to/file", O_RDWR);

// mixture of:
write(fd, ...);
lseek(fd, ...);
read (fd, ...);
// etc

...

// make file read-only ???

read (fd, ...); // OK
lseek(fd, ...); // OK
write(fd, ...); // error

Solution

  • This is not possible at least through call to fcntl as the POSIX docs says (emphasis is mine):

    fcntl():

    F_SETFL

    Set the file status flags, defined in fcntl.h, for the file description associated with fildes from the corresponding bits in the third argument, arg, taken as type int. Bits corresponding to the file access mode and the file creation flags, as defined in fcntl.h, that are set in arg shall be ignored. If any bits in arg other than those mentioned here are changed by the application, the result is unspecified.

    and

    fcntl.h

    O_ACCMODE Mask for file access modes.

    The header shall define the following symbolic constants for use as the file access modes for open(), openat(), and fcntl(). The values shall be unique, except that O_EXEC and O_SEARCH may have equal values. The values shall be suitable for use in #if preprocessing directives.

    O_EXEC Open for execute only (non-directory files). The result is unspecified if this flag is applied to a directory.

    O_RDONLY Open for reading only.

    O_RDWR Open for reading and writing.

    O_SEARCH Open directory for search only. The result is unspecified if this flag is applied to a non-directory file.

    O_WRONLY Open for writing only.