Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 12-11-2012 #1
- Join Date
- Apr 2009
Single access single resource in programming
I am new in linux. I have written a program to read and write into file. I have created same two programs, which can simultaneously access same file. How can i ensure that only single program can access the file at a time.when other program try to access the file, then i should show that file is already used and wait until it is not released.
Can i anybody tell the solution to problem.
- 12-12-2012 #2
- Join Date
- Dec 2009
There are a lot of options.
The simplest one is to call flock(fd,LOCK_EX) from both programs before writing to the file. If the second
Call flock(fd,LOCK_UN) when the process is finished writing to the file.
If process A holds the lock and process B calls flock, then it will block until the lock is released by process A.
The lock is "advisory". That means that if process A holds the lock, process B will not be prevented from writing to the file if it doesn't call flock. On most unix systems, you can make the locking "mandatory" by setting setgid permissions on the file before the programs are run:
$ chmod 2644 myFile