user357498
user357498

Reputation: 149

How can I lock a directory in C on a linux machine

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

Answers (2)

rustyx
rustyx

Reputation: 85541

Will flock or lockf work on a directory?

flock - yes, lockf - no.

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

Celada
Celada

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

Related Questions