Reputation: 149
Will flock or lockf work on a directory? I there another way to lock a directory in C on a linux machine?
Upvotes: 8
Views: 10562
Reputation: 85541
Will
flock
orlockf
work on a directory?
You can open the directory for reading and get an advisory exclusive lock using flock
:
int fd = open("somedir", O_RDONLY);
if (flock(fd, LOCK_EX | LOCK_NB) == 0) {
// success
} else {
// failed
}
But you can't open a directory for writing, which means you can't get a fcntl
-style exclusive lock on it, neither advisory nor mandatory.
Of course, if you actually need to prevent shared access to a directory, that's an entirely different question from locking - you can change its permissions, rename it, lock the entire filesystem, use IPC, etc.
Upvotes: 1
Reputation: 22261
You can't open a directory for writing, so that means you can't get a write lock on it.
Even if you could, please keep in mind that flock
and fcntl
and other kinds of POSIX locks are advisory, so they don't actually prevent software that doesn't respect the lock from doing things.
Maybe you want to look at something like xfs_freeze
which locks an entire filesystem. It's probably not useful for your use case though.
Upvotes: 1