Skip to content

Commit

Permalink
perf(file): simplify the usage of flock
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Sep 9, 2023
1 parent 00c5779 commit b89e753
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 19 deletions.
25 changes: 8 additions & 17 deletions examples/flock.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,26 @@

local file = require 'eco.file'
local time = require 'eco.time'
local sys = require 'eco.sys'

local fd, err = file.open('/tmp/lock-test', file.O_RDWR)
if not fd then
print('open fail:', err)
return
end

while true do
local ok, errno, err = file.flock(fd, file. LOCK_EX)
if ok then
print('lock ok')
break
end

if errno ~= sys.EAGAIN then
print('lock fail:', err)
file.close(fd)
return
end
time.sleep(0.1)
local ok, err = file.flock(fd, file.LOCK_EX)
if not ok then
print('lock fail:', err)
file.close(fd)
return
end

print('locked')

time.sleep(5)

file.flock(fd, file. LOCK_UN)
file.flock(fd, file.LOCK_UN)

print('unlocked')

time.sleep(5)

file.close(fd)
3 changes: 1 addition & 2 deletions file.c
Original file line number Diff line number Diff line change
Expand Up @@ -443,8 +443,7 @@ static int eco_file_flock(lua_State *L)
if (flock(fd, operation | LOCK_NB)) {
lua_pushnil(L);
lua_pushinteger(L, errno);
lua_pushstring(L, strerror(errno));
return 3;
return 2;
}

lua_pushboolean(L, true);
Expand Down
27 changes: 27 additions & 0 deletions file.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
-- Author: Jianhui Zhao <zhaojh329@gmail.com>

local file = require 'eco.core.file'
local sys = require 'eco.core.sys'
local time = require 'eco.time'

local M = {}

Expand Down Expand Up @@ -78,4 +80,29 @@ function M.write(fd, data)
return file.write(fd, data)
end

function M.flock(fd, operation, timeout)
local deadtime

if timeout then
deadtime = sys.uptime() + timeout
end

while true do
local ok, errno = file.flock(fd, operation)
if ok then
return true
end

if errno ~= sys.EAGAIN then
return false, sys.strerror(errno)
end

if deadtime and sys.uptime() > deadtime then
return false, 'timeout'
end

time.sleep(0.001)
end
end

return setmetatable(M, { __index = file })

0 comments on commit b89e753

Please sign in to comment.