Find the answer to your Linux question:
Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By abarclay
Hi, 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 ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Apr 2009
    Posts
    7

    Single access single resource in programming


    Hi,
    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.

    Thanks
    Sukhdeep

  2. #2
    Just Joined!
    Join Date
    Dec 2009
    Location
    California
    Posts
    98
    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
    CaptainDangeax likes this.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •