/
file.lua
84 lines (63 loc) 路 1.46 KB
/
file.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
-- SPDX-License-Identifier: MIT
-- Author: Jianhui Zhao <zhaojh329@gmail.com>
local file = require 'eco.core.file'
local sys = require 'eco.core.sys'
local bufio = require 'eco.bufio'
local time = require 'eco.time'
local M = {}
function M.readfile(path, m)
local f, err = io.open(path, 'r')
if not f then
return nil, err
end
local data, err = f:read(m or '*a')
f:close()
if not data then
return nil, err
end
return data
end
function M.writefile(path, data, append)
local m = 'w'
if append then
m = 'a'
end
local f, err = io.open(path, m)
if not f then
return nil, err
end
local n, err = f:write(data)
f:close()
if not n then
return nil, err
end
return n
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
function M.sync()
local pid, err = sys.exec('sync')
if not pid then
return nil, err
end
eco.watcher(eco.CHILD, pid):wait()
return true
end
return setmetatable(M, { __index = file })