jbe@435: --[[ jbe@435: jbe@435: This file contains an alternative pfilter(...) implementation in pure Lua (utilizing moonbridge_io). This implementation is currently not used since extos already comes with a C implementation (extos.pfilter), which is independent of moonbridge_io and thus preferred to the implementation below. jbe@435: jbe@435: data_out, -- string containing stdout data, or nil in case of error jbe@435: data_err, -- string containing error or stderr data jbe@435: status = -- exit code, or negative code in case of abnormal termination jbe@435: pfilter( jbe@435: data_in, -- string containing stdin data jbe@435: filename, -- executable jbe@435: arg1, -- first (non-zero) argument to executable jbe@435: arg2, -- second argument to executable jbe@435: ... jbe@435: ) jbe@435: jbe@435: Executes the executable given by "filename", passing optional arguments. A given string may be fed into the program as stdin. On success 3 values are returned: A string containing all stdout data of the sub-process, a string containing all stderr data of the sub-process, and a status code. The status code is negative, if the program didn't terminate normally. By convention a status code of zero indicates success, while positive status codes indicate error conditions. If program execution was not possible at all, then nil is returned as first value and an error string as second value. jbe@435: jbe@435: --]] jbe@435: jbe@435: return function(data_in, ...) jbe@435: local process, errmsg = moonbridge_io.exec(...) jbe@435: if not process then return nil, errmsg end jbe@435: local read_fds = {[process.stdout] = true, [process.stderr] = true} jbe@435: local write_fds = {[process.stdin] = true} jbe@435: local function read(socket, chunks) jbe@435: if read_fds[socket] then jbe@435: local chunk, status = socket:read_nb() jbe@435: if not chunk then jbe@435: socket:close() jbe@435: read_fds[socket] = nil jbe@435: else jbe@435: chunks[#chunks+1] = chunk jbe@435: if status == "eof" then jbe@435: socket:close() jbe@435: read_fds[socket] = nil jbe@435: end jbe@435: end jbe@435: end jbe@435: end jbe@435: local function write(...) jbe@435: if write_fds[process.stdin] then jbe@435: local buffered = process.stdin:flush_nb(...) jbe@435: if not buffered or buffered == 0 then jbe@435: process.stdin:close() jbe@435: write_fds[process.stdin] = nil jbe@435: end jbe@435: end jbe@435: end jbe@435: write(data_in or "") jbe@435: local stdout_chunks, stderr_chunks = {}, {} jbe@435: while next(read_fds) or next(write_fds) do jbe@435: moonbridge_io.poll(read_fds, write_fds) jbe@435: read(process.stdout, stdout_chunks) jbe@435: read(process.stderr, stderr_chunks) jbe@435: write() jbe@435: end jbe@435: return jbe@435: table.concat(stdout_chunks), jbe@435: table.concat(stderr_chunks), jbe@435: process:wait() jbe@435: end jbe@435: