# lock_file

Definition: | integer i1 = lock_file(integer fn, integer locktype, sequence range)
Description: | When multiple processes or threads 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.
pwa/p2js: | Not supported.
Comments: | 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. Under Linux, there are two types of locks that you can request using the locktype parameter. Under Windows the locktype parameter is ignored, but should be an integer. 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. The following constants are pre-defined:
    global constant LOCK_SHARED = 1,
                    LOCK_EXCLUSIVE = 2
On Windows you can lock a specified portion of a file using the range parameter. range 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. In the current release for Linux, locks always apply to the whole file, and you should specify {} for this parameter. If it is successful in obtaining the desired lock, lock_file() will return true (1), otherwise false (0). 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, possibly with a short sleep() between tries. On Linux, 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: |
    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(1, "One minute already ... I can't wait forever!\n")
            abort(1)
        end if
        sleep(5) -- let other processes run
    end while
    puts(v, "Yet another visitor\n")
    unlock_file(v, {})
    close(v)
Implementation: | via :%opLock / flock_file() in builtins\VM\pfileioN.e (an autoinclude) - be warned however it is low-level complicated stuff that you do not need to know.
See Also: | unlock_file, flush, sleep