Process Lua:如何检查进程是否正在运行
我想从Lua启动一个进程,并监视该进程是否仍在运行 [编辑]Process Lua:如何检查进程是否正在运行,process,lua,Process,Lua,我想从Lua启动一个进程,并监视该进程是否仍在运行 [编辑] 我知道启动可以通过os:execute实现,但这是阻塞。我想找到一种无阻塞启动进程并监视它是否仍在运行的方法。其中一种简单的方法就是使用和监视它的输出,或者使用其他Linux工具(例如)自行处理它们 另一种方法是使用一些luaposix绑定,如和。下面的Lua库提供了(异步)启动和监视进程的函数 Lua中的协同程序允许您做您需要的事情(自Lua 5.0以来): 如果您使用的是luajit,那么可以使用外部函数接口直接调用OS api函
我知道启动可以通过os:execute实现,但这是阻塞。我想找到一种无阻塞启动进程并监视它是否仍在运行的方法。其中一种简单的方法就是使用和监视它的输出,或者使用其他Linux工具(例如)自行处理它们
另一种方法是使用一些luaposix绑定,如和。下面的Lua库提供了(异步)启动和监视进程的函数
Lua中的协同程序允许您做您需要的事情(自Lua 5.0以来):
如果您使用的是luajit,那么可以使用外部函数接口直接调用OS api函数。e、 g.适用于Linux或类似系统
local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
int fork(void);
int execlp(const char* file, const char *arg, ...);
int waitpid(int pid, int *status, int options);
void _exit(int status);
unsigned int sleep(unsigned int seconds);
]]
local pid = C.fork()
if pid > 0 then -- parent
print("Waiting for child process:");
local status = ffi.new('int[1]')
local WNOHANG = 1
local done = false
while not done do
local id = C.waitpid(-1, status, WNOHANG)
if id == pid then
done = true
elseif pid < 0 then
print("error occurred")
os.exit(-1)
else
print("status=",status[0])
C.sleep(1)
-- do other stuff. We aren't waiting
end
end
print("Child exited with status=", status[0])
elseif pid == 0 then -- child
print("Starting child")
C.execlp('sleep', 'sleep', '5')
C._exit(-1) -- exec never returns
elseif pid < 0 then -- failure
print("failed to fork")
end
本地外国金融机构=要求(“外国金融机构”)
本地C=外国金融机构C
外国金融机构[[
int fork(void);
int execlp(常量字符*文件,常量字符*参数,…);
int waitpid(int pid,int*状态,int选项);
无效退出(int状态);
无符号整数睡眠(无符号整数秒);
]]
本地pid=C.fork()
如果pid>0,则--parent
打印(“等待子进程:”);
本地状态=ffi.new('int[1]”)
局部WNOHANG=1
本地完成=错误
虽然还没做完,但要做
本地id=C.waitpid(-1,状态,WNOHANG)
如果id==pid,那么
完成=正确
如果pid小于0,则
打印(“发生错误”)
操作系统退出(-1)
其他的
打印(“status=,status[0])
C.睡眠(1)
--做其他事情。我们没有等
结束
结束
打印(“子项已退出,状态为“”,状态为[0])
elseif pid==0然后--子对象
打印(“起始子项”)
C.execlp('sleep','sleep','5')
C._退出(-1)--exec永远不会返回
elseif pid<0则--失败
打印(“未能分叉”)
结束
您将看到,使用WNOHANG=1,您仍然可以返回一个结果,查看孩子是否已退出,然后继续执行其他操作。uf,您应该提到,您需要它专门用于Windows:)
local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
int fork(void);
int execlp(const char* file, const char *arg, ...);
int waitpid(int pid, int *status, int options);
void _exit(int status);
unsigned int sleep(unsigned int seconds);
]]
local pid = C.fork()
if pid > 0 then -- parent
print("Waiting for child process:");
local status = ffi.new('int[1]')
local WNOHANG = 1
local done = false
while not done do
local id = C.waitpid(-1, status, WNOHANG)
if id == pid then
done = true
elseif pid < 0 then
print("error occurred")
os.exit(-1)
else
print("status=",status[0])
C.sleep(1)
-- do other stuff. We aren't waiting
end
end
print("Child exited with status=", status[0])
elseif pid == 0 then -- child
print("Starting child")
C.execlp('sleep', 'sleep', '5')
C._exit(-1) -- exec never returns
elseif pid < 0 then -- failure
print("failed to fork")
end