I have a function like this which aims to read a file:
int foo(FILE* f)
I want to use flock
in order to prevent TOCTTOU. flock
requires a file descriptor as an integer. I can get this using fileno(file)
. The implementation of foo
therefore might look like this:
int foo(FILE* f) {
if(!f) return -1;
int fd = fileno(f);
if(fd < 0) return -1;
flock(fd, LOCK_EX);
//do all the reading stuff and so on.
}
However, the evil user might do something like this:
FILE* test;
test = fopen("someexistingfile.txt", "r");
fclose(test);
foo(test);
Then I have a problem because fileno
will do invalid reads according to valgrind because it assumes that the file is open.
Any ideas on how to check whether the file is closed?