tags:

views:

387

answers:

3

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

+1  A: 

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

Ignacio Vazquez-Abrams
+4  A: 

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.

Emil Ivanov
i've tried them , they are very good thanks
madicemickael
+4  A: 

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.

Even though file locks are bound to processes, you can use a mutex in your threaded application to make sure one thread doesn't release a lock created by another.
roguenut