In my C program, I am reading from a file line by line.
FILE *file = fopen("config.txt", "r");
if (file)
{
char *line;
size_t length;
size_t read;
int test_case_number = 0;
while ((read = getline(&line, &length, file)) != -1)
{
printf("%s", line);
}
}
else
{
fputs("The provided <PATH_TO_CONFIG FILE> does not exist.\n\n");
exit(1);
}
However, while I am reading this file, I want to prevent any other process from writing to config.txt while its being read. How can I do this?
If you have to "defend" against your own processes or "well behaved" processes, then you want to use flock:
fp = fopen(fileName, fileMode);
if (fp != NULL) {
flock(fileno(fp), LOCK_EX);
...
fclose(fp); fp = NULL;
}
But those locks are advisory only, that is, any other process can choose to ignore them. Or not bother checking. I've just tried creating a file, opening it and locking with LOCK_EX, then sleeping for 60 seconds. During that time, another process was free to do whatever it wanted to the file (Linux, Ubuntu 18.04-LTS).
But if you need mandatory locking, that's not something that is available on all platforms since the kernel has to cooperate. Here you will find a description and example on how the limited mandatory lock support in Linux can be used.
On the other hand, in Windows this is automatic:
Windows defaults to automatic, mandatory file locking. UNIXes default to manual, cooperative file locking. In both cases, the defaults can be overridden, but in both cases they usually aren’t. (source).
A workaround can be to temporarily rename the file being worked on to a unique name, possibly creating an empty file with the old name in its place, then renaming it back once you've done; or copying the file as above, leaving a copy for other programs to read. Write denial can also be achieved by changing the file permissions. These solutions require to handle some edge cases, e.g. where your process crashes or the machine hangs before setting things back as they were.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With