radu florescu
radu florescu

Reputation: 4363

Locking files in linux with c/c++

I am wondering if you can : lock only a line or a single character in a file in linux and the rest of the file should remain accessible for other processes? I received a task regarding simulating transaction on a file with c/c++ under linux . Please give me an answer and if this answer is yes ,give me some links from where i could take a peek to make this task.

Thanks, Madicemickael

Upvotes: 9

Views: 19352

Answers (3)

Emil Ivanov
Emil Ivanov

Reputation: 37643

Yes, this is possible.

The Unix way to do this is via fcntl or lockf. Whatever you choose, make sure to use only it and not mix the two. Have a look at this question (with answer) about it: fcntl, lockf, which is better to use for file locking?.

If you can, have a look at section 14.3 in Advanced Programming in the UNIX Environment.

Upvotes: 15

user175104
user175104

Reputation: 3696

fcntl() is the one API to choose, since it is the least broken and is POSIX. It is the only one that works across NFS. That said it is a complete disaster, too, since locks are bound to processes, not file descriptors. That means that if you lock a file and then some other thread or some library function locks/unlocks it, your lock will be broken too. Also, you cannot use file system locks to protect two threads of the same process to interfere with each other. Also, you should not use file locks on files that are accessible to more than one user, because that effectively enables users to freeze each others processes.

In summary: file locking on Unix creates more problems than it solves. Before you use it you need to be really sure you fully understand the semantics.

Upvotes: 19

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799240

lockf(3) can apply a lock to a section of a file.

Upvotes: 3

Related Questions