Reopen a read-only file on Linux (or POSIX)

I open the file in read / write mode and perform a series of read, write and search operations (from user input).

At some point later, I want to make the file read-only to prevent it from being written further.

Is there a Linux (or POSIX) function for this? Perhaps some challenge fcntl?

Or is my only option is to save the current position in the file, close it and reopen it 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
+4
source share
1 answer

This is not possible, at least in a call fcntl, as the POSIX docs say (emphasize that this is mine):

fcntl():

F_SETFL

, fcntl.h, , , arg, int. , , fcntl.h, arg, . - arg, , , .

fcntl.h

O_ACCMODE .

open(), openat() fcntl(). , , O_EXEC O_SEARCH . #if .

O_EXEC ( ). unspecified, . O_RDONLY .

O_RDWR .

O_SEARCH . , .

O_WRONLY .

+4

Source: https://habr.com/ru/post/1683864/


All Articles