-
Notifications
You must be signed in to change notification settings - Fork 13
/
sys.lua
74 lines (57 loc) · 1.51 KB
/
sys.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
-- SPDX-License-Identifier: MIT
-- Author: Jianhui Zhao <[email protected]>
local file = require 'eco.core.file'
local sys = require 'eco.core.sys'
local bufio = require 'eco.bufio'
local M = {}
local exec_methods = {}
function exec_methods:release()
if not self.stdout_fd then
return
end
file.close(self.stdout_fd)
file.close(self.stderr_fd)
self.stdout_fd = nil
self.stderr_fd = nil
end
function exec_methods:wait(timeout)
return self.child_w:wait(timeout or 30.0)
end
function exec_methods:pid()
return self.__pid
end
function exec_methods:read_stdout(pattern, timeout)
return self.stdout_b:read(pattern, timeout)
end
function exec_methods:read_stderr(pattern, timeout)
return self.stderr_b:read(pattern, timeout)
end
local exec_metatable = {
__index = exec_methods,
__gc = exec_methods.release
}
function M.exec(...)
local pid, stdout_fd, stderr_fd = sys.exec(...)
if not pid then
return nil, stdout_fd
end
return setmetatable({
__pid = pid,
stdout_fd = stdout_fd,
stderr_fd = stderr_fd,
child_w = eco.watcher(eco.CHILD, pid),
stdout_b = bufio.new(stdout_fd),
stderr_b = bufio.new(stderr_fd)
}, exec_metatable)
end
function M.signal(sig, cb, ...)
local w = eco.watcher(eco.SIGNAL, sig)
eco.run(function(...)
while true do
if not w:wait() then return end
cb(...)
end
end, ...)
return w
end
return setmetatable(M, { __index = sys })