我需要使用Lua来运行一个二进制程序,该程序可以在其stdout中写入一些内容并返回一个状态代码(也称为" 退出状态 ").
我在网上搜索,找不到能满足我需要的东西.但是我发现在Lua:
os.execute() 返回状态代码io.popen() 返回一个可用于读取进程输出的文件处理程序但是我需要两者.编写一个在场景后面运行两个函数的包装函数不是一个选项,因为进程开销和连续运行时结果可能会发生变化.我需要写一个这样的函数:
function run(binpath)
...
return output,exitcode
end
Run Code Online (Sandbox Code Playgroud)
有谁知道如何解决这个问题?
PS.目标系统响了Linux.
gns*_*ank 14
使用LUA 5.2,我可以执行以下操作
-- This will open the file
local file = io.popen('dmesg')
-- This will read all of the output, as always
local output = file:read('*all')
-- This will get a table with some return stuff
-- rc[1] will be true, false or nil
-- rc[3] will be the signal
local rc = {file:close()}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助...
我不能使用Lua 5.2,我使用这个辅助函数。
function execute_command(command)
local tmpfile = '/tmp/lua_execute_tmp_file'
local exit = os.execute(command .. ' > ' .. tmpfile .. ' 2> ' .. tmpfile .. '.err')
local stdout_file = io.open(tmpfile)
local stdout = stdout_file:read("*all")
local stderr_file = io.open(tmpfile .. '.err')
local stderr = stderr_file:read("*all")
stdout_file:close()
stderr_file:close()
return exit, stdout, stderr
end
Run Code Online (Sandbox Code Playgroud)