-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessManager.lua
More file actions
55 lines (51 loc) · 1.63 KB
/
Copy pathprocessManager.lua
File metadata and controls
55 lines (51 loc) · 1.63 KB
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
local function getOSExecuteResult(command)
local fs = io.popen(command)
assert(fs, ("getOSExecuteResult given malformed command '%s'"):format(command))
local result = fs:read("*all")
fs:close()
return result
end
local function stripQuotes(str)
return str:gsub("%b\"\"", function(n) return n:sub(2, -2) end)
end
local function cleanMagicCharacters(str)
return str:gsub("[%$%%%^%*%(%)%.%[%]%[%+%-%?]", {
["$"] = "%$",
["%"] = "%%",
["^"] = "%^",
["*"] = "%*",
["("] = "%(",
[")"] = "%)",
["."] = "%.",
["["] = "%[",
["]"] = "%]",
["+"] = "%+",
["-"] = "%-",
["?"] = "%?"
})
end
local function cleanString(str)
return cleanMagicCharacters(stripQuotes(str))
end
-- Small module for managing spawned processes, not meant to be used elsewhere
-- Note that this assumes the use of unique process names + arguments
-- i.e. if a process `/usr/lib/firefox` is spawned, no other processes of this name should exist
local processManager = {}
processManager.__index = processManager
function processManager.new()
return setmetatable({}, processManager)
end
function processManager:kill(pid)
if not pid or not self[pid] then return end
os.execute("kill " .. pid)
self[pid] = nil
end
function processManager:spawn(cmd)
os.execute(("%s &"):format(cmd))
local pid = getOSExecuteResult(("pgrep %s -a"):format(cmd:match("[^%s]+"))):match("(%d+)%s+" .. cleanString(cmd))
print(getOSExecuteResult(("pgrep %s -a")))
print("(%d+)%s+" .. cleanString(cmd))
self[pid] = cmd
return pid
end
return processManager.new()