0
votes

How to block file when you reading it (by fopen or open in linux), to prevent any modifications during reading?

What i have: 1 file with data; I want to read data from it in my function, so i use fopen():

FILE *file = fopen(fileName, "r"); Now i need something to block my file - any (or only current user's as variant) another process mustn't have any access (or only modify it as variant) to it until my function will allow them to do it

I suppose, i can do that using set chmod flags for them and setting them back after work; Or using open() function with special flags arguments, but it's not desirable because i would like to work with fgets() in function;

Is there any examples of how to do it?

1
See advisory and mandatory file locking. If you want to prevent access from pgm outside of your control (i.e. you didn't write or can't change them) then you probably want mandatory locking but consider whether you really require that since you have to do some things to the filesystem first. See flock, fcntl, etc.Duck
Possible duplicate of How do I lock files using fopen()?jww

1 Answers

2
votes

Yes, you can use flock to do this. However, since you want to open the file with fopen instead of open, you'll need to first get the file descriptor using fileno. For example:

FILE* f = fopen(...);
int fd = fileno(f);
// flock should return zero on success
flock(fd, LOCK_EX);

That would place an exclusive lock - if you want a shared lock, change LOCK_EX to LOCK_SH.