Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking files in linux with c/c++

Tags:

c++

c

linux

locking

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

like image 668
radu florescu Avatar asked Jan 13 '10 15:01

radu florescu


People also ask

How do I lock a file in Linux?

To enable mandatory file locking in Linux, two requirements must be satisfied: We must mount the file system with the mand option (mount -o mand FILESYSTEM MOUNT_POINT). We must turn on the set-group-ID bit and turn off the group-execute bit for the files we are about to lock (chmod g+s,g-x FILE).

What is flock in C?

The flock() function applies or removes an advisory lock on the file associated with the open file descriptor filedes . Advisory locks allow cooperating processes to perform consistent operations on files, but they don't guarantee consistency. The locking mechanism allows two types of locks: shared and exclusive.

What is write lock for a file?

An exclusive or write lock gives a process exclusive access for writing to the specified part of the file. While a write lock is in place, no other process can lock that part of the file. A shared or read lock prohibits any other process from requesting a write lock on the specified part of the file.


2 Answers

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.

like image 153
user175104 Avatar answered Sep 21 '22 18:09

user175104


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.

like image 33
Emil Ivanov Avatar answered Sep 24 '22 18:09

Emil Ivanov