lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mon, Oct 28, 2013 at 01:05:31PM -0400, Rena wrote:
> I see, but what if the process I want to spawn isn't another Lua process?
> I've tried this:
...use dup2 to redirect fd 0 / fd 1 of the exec'd 
process (ping in your case) to the file descriptors opened
by pipe (in the child part), just like you would do in 
plain C / posix. Note that this requires a recent luaposix
(my ubuntu 12.04 packaged version does not contain dup2).

Be nice, kill (and wait for) child pid when you're done:

#!/usr/bin/env lua5.1
local posix = require('posix')
local function spawn(program, ...)
    local read, write = posix.pipe()
    local cpid = posix.fork()
    if cpid == 0 then --child
				assert(0 == posix.dup2(read,0))
				assert(1 == posix.dup2(write,1))
        assert(posix.execp(program, ...))
    else return {read=read, write=write, pid=cpid}
    end
end

local proc = assert(spawn('ping', '127.0.0.1'))
local cnt
for cnt = 1,10,1 do
    local data = assert(posix.read(proc.read, 1024))
    print("ping says:", data)
end
posix.kill(proc.pid)
posix.wait(proc.pid)