Blame examples/lock.lua

Packit 437b5e
local p = require "posix"
Packit 437b5e
local fd = p.creat("file.txt", "rw-r--r--")
Packit 437b5e
Packit 437b5e
-- Set lock on file
Packit 437b5e
local lock = {
Packit 437b5e
    l_type = p.F_WRLCK;     -- Exclusive lock
Packit 437b5e
    l_whence = p.SEEK_SET;  -- Relative to beginning of file
Packit 437b5e
    l_start = 0;            -- Start from 1st byte
Packit 437b5e
    l_len = 0;              -- Lock whole file
Packit 437b5e
  }
Packit 437b5e
local result = p.fcntl(fd, p.F_SETLK, lock)
Packit 437b5e
if result == -1 then
Packit 437b5e
  error("file locked by another process")
Packit 437b5e
end
Packit 437b5e
Packit 437b5e
-- Do something with file while it's locked
Packit 437b5e
p.write(fd, "Lorem ipsum\n")
Packit 437b5e
Packit 437b5e
-- Release the lock
Packit 437b5e
lock.l_type = p.F_UNLCK
Packit 437b5e
p.fcntl(fd, p.F_SETLK, lock)