updating oE lock_file


include io.e 
namespace io 
public function lock_file(file_number fn, lock_type t, byte_range r = {}) 

locks a file so access is restricted.

  1. fn : an integer, the handle to the file or device to (partially) lock.
  2. t : an integer which defines the kind of lock to apply.
  3. r : a sequence, defining a section of the file to be locked, or {} for the whole file (the default).

An integer, 0 on failure, 1 on success.


The target file or device must be open.


When multiple processes can simultaneously access a file, some kind of locking mechanism may be needed to avoid mangling the contents of the file, or causing erroneous data to be read from the file.

lock_file attempts to place a lock on an open file, fn, to stop other processes from using the file while your program is reading it or writing it.

There are two types of locks that you can request using the t parameter. Ask for a shared lock when you intend to read a file, and you want to temporarily block other processes from writing it. Ask for an exclusive lock when you intend to write to a file and you want to temporarily block other processes from reading or writing it. It is ok for many processes to simultaneously have shared locks on the same file, but only one process can have an exclusive lock, and that can happen only when no other process has any kind of lock on the file. io.e contains the following declarations:

public enum 

On /Windows you can lock a specified portion of a file using the r parameter. r is a sequence of the form: {first_byte, last_byte}. It indicates the first byte and last byte in the file, that the lock applies to. Specify the empty sequence {}, if you want to lock the whole file, or don't specify it at all, as this is the default. In the current release for Unix, locks always apply to the whole file, and you should use this default value.

lock_file does not wait for other processes to relinquish their locks. You may have to call it repeatedly, before the lock request is granted.

On Unix, these locks are called advisory locks, which means they are not enforced by the operating system. It is up to the processes that use a particular file to cooperate with each other. A process can access a file without first obtaining a lock on it. On Windows locks are enforced by the operating system.

Example 1:
include std/io.e 
integer v 
atom t 
v = open("visitor_log", "a")  -- open for append 
t = time() 
while not lock_file(v, LOCK_EXCLUSIVE, {}) do 
    if time() > t + 60 then 
        puts(STDOUT, "One minute already ... I can't wait forever!\n") 
    end if 
    sleep(5) -- let other processes run 
end while 
puts(v, "Yet another visitor\n") 
unlock_file(v, {}) 
See Also:


Not Categorized, Please Help


Quick Links

User menu

Not signed in.

Misc Menu