Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting return status AND program output

Tags:

lua

I need to use Lua to run a binary program that may write something in its stdout and also returns a status code (also known as "exit status").

I searched the web and couldn't find something that does what I need. However I found out that in Lua:

  • os.execute() returns the status code
  • io.popen() returns a file handler that can be used to read process output

However I need both. Writing a wrapper function that runs both functions behind the scene is not an option because of process overhead and possibly changes in result on consecutive runs. I need to write a function like this:

function run(binpath)
    ...
    return output,exitcode
end

Does anyone has an idea how this problem can be solved?

PS. the target system rung Linux.

like image 534
AlexStack Avatar asked Sep 30 '11 07:09

AlexStack


1 Answers

This is how I do it.

local process = io.popen('command; echo $?') -- echo return code of last run command
local lastline
for line in process:lines() do
    lastline = line
end
print(lastline) -- the return code is the last line of output

If the last line has fixed length you can read it directly using file:seek("end", -offset), offset should be the length of the last line in bytes.

like image 104
theJian Avatar answered Oct 25 '22 20:10

theJian