webmcp

view libraries/extos/pfilter.lua @ 435:f704f35923e2

Added a (currently unused) pure Lua version of extos.pfilter(...)
author jbe
date Sat Jan 16 04:44:16 2016 +0100 (2016-01-16)
parents
children 87c87be92154
line source
1 --[[
3 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.
5 data_out, -- string containing stdout data, or nil in case of error
6 data_err, -- string containing error or stderr data
7 status = -- exit code, or negative code in case of abnormal termination
8 pfilter(
9 data_in, -- string containing stdin data
10 filename, -- executable
11 arg1, -- first (non-zero) argument to executable
12 arg2, -- second argument to executable
13 ...
14 )
16 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.
18 --]]
20 return function(data_in, ...)
21 local process, errmsg = moonbridge_io.exec(...)
22 if not process then return nil, errmsg end
23 local read_fds = {[process.stdout] = true, [process.stderr] = true}
24 local write_fds = {[process.stdin] = true}
25 local function read(socket, chunks)
26 if read_fds[socket] then
27 local chunk, status = socket:read_nb()
28 if not chunk then
29 socket:close()
30 read_fds[socket] = nil
31 else
32 chunks[#chunks+1] = chunk
33 if status == "eof" then
34 socket:close()
35 read_fds[socket] = nil
36 end
37 end
38 end
39 end
40 local function write(...)
41 if write_fds[process.stdin] then
42 local buffered = process.stdin:flush_nb(...)
43 if not buffered or buffered == 0 then
44 process.stdin:close()
45 write_fds[process.stdin] = nil
46 end
47 end
48 end
49 write(data_in or "")
50 local stdout_chunks, stderr_chunks = {}, {}
51 while next(read_fds) or next(write_fds) do
52 moonbridge_io.poll(read_fds, write_fds)
53 read(process.stdout, stdout_chunks)
54 read(process.stderr, stderr_chunks)
55 write()
56 end
57 return
58 table.concat(stdout_chunks),
59 table.concat(stderr_chunks),
60 process:wait()
61 end

Impressum / About Us