获取返回状态和程序输出

Ale*_*ack 10 lua

我需要使用Lua来运行一个二进制程序,该程序可以在其stdout中写入一些内容并返回一个状态代码(也称为" 退出状态 ").

我在网上搜索,找不到能满足我需要的东西.但是我发现在Lua:

但是我需要两者.编写一个在场景后面运行两个函数的包装函数不是一个选项,因为进程开销和连续运行时结果可能会发生变化.我需要写一个这样的函数:

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)

希望这可以帮助...

  • 遗憾的是,这在 NGINX 中不起作用:/,请参阅:https://github.com/openresty/lua-nginx-module/issues/779 (2认同)

Dav*_*Qin 5

我不能使用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)

  • 您可以使用 os.tmpname() 来获取独立于操作系统的临时文件名,并确保具有写访问权限。在这种情况下,必须在使用后将其删除(os.remove)。如果您坚持使用 lua 5.1,这是我针对此问题找到的最佳解决方案(主要缺点是您无法为长时间运行的进程和/或具有大量输出的进程传输输出) (3认同)