[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

RE: Files

On Thu, 7 Dec 2000, Harpreet Singh (RBIN/DCA-NMP) wrote:
> Ok, so two processes can access the same file at the same time.
> If both open it for reading there is no problem. But If one opens it for
> reading
> and one for writing, won't there be a problem.
> Also is it possible to lock a file. In the sense that if it has been opened
> it cannot be used by another
> program or process.

Yes, it's possible to lock the file. You can have agreement between
processess (provided, all of them are your custom processess), u can have
mutual agreement btween the processes on writing to the file. Let's say
you have 2 procs. A & B which wants to access the file X

* Whenever A or B wants to access the file, they would lock the file &
  then perform the operation (reading/writing).
* After the operation, the lock would be removed.

Now there are diferent ways of locking.
1. Create a symlink b4 locking. After the operation, delete the
symlink. B4 creating the symlink, see whether the symlink already exist,
in which case it means the file is already locked & you need to wait to
get it unlocked (wait for deletion of symlink).

2. Use semaphores to lock/unlock. A semaphore is like a counter, which can
be incremented or decremented. Whenever a proc. wants to use a resource,
it first decrements the resource counter (ie. sem count) & then uses the
file. After performing the operation, the resource counter is
incremented. The operation of inc./dec. is performed by the kernel in one
atomic operation. See 'man semctl/semop/semget' for details.

3. Use flock to lock & unlock. flock locks the inode of the file. See man
flock for details.