I'm writing unit tests for a function that may lock a file (using fcntl(fd, F_SETLK, ...)
) under some conditions.
I want my unit test to be able to EXPECT that the file is or is not locked at certain points. But I can't find any way to test that. I've tried using F_GETLK
, but it will only tell you if the lock would not be able to be placed. Since a given process can re-lock the same file as often as it wants, F_GETLK
is returning F_UNLCK
, indicating the file is unlocked.
For instance, if I run the following little program:
int main(int argc, char** argv) {
int fd = open("/tmp/my_test_file", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd < 0) {
return EXIT_FAILURE;
}
// Initial lock
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0; // Lock entire file.
if (fcntl(fd, F_SETLK, &lock) < 0) {
return EXIT_FAILURE;
}
// Test lock:
lock.l_type = F_WRLCK;
lock.l_pid = 0;
if (fcntl(fd, F_GETLK, &lock) < 0) {
return EXIT_FAILURE;
}
switch (lock.l_type) {
case F_WRLCK:
std::cout << lock.l_pid << " is holding the lock\n";
break;
case F_UNLCK:
std::cout << "File is unlocked\n";
break;
default:
std::cout << "Unexpected " << lock.l_type << "\n";
break;
}
return EXIT_SUCCESS;
}
It will print:
File is unlocked
So, is there a way for a process to test if it is holding an fcntl
file lock?
Also, are there other kinds of (Linux-portable!) file locks I could be using that would solve my problem?