webmcp

view libraries/extos/pfilter.lua @ 507:ac5f7a40b8c4

Extended documentation (mostly on "Configuration, pre-fork and post-fork initializers")
author jbe
date Sun Aug 20 23:12:16 2017 +0200 (2017-08-20)
parents 87c87be92154
children
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 if chunk ~= "" then
33 chunks[#chunks+1] = chunk
34 end
35 if status == "eof" then
36 socket:close()
37 read_fds[socket] = nil
38 end
39 end
40 end
41 end
42 local function write(...)
43 if write_fds[process.stdin] then
44 local buffered = process.stdin:flush_nb(...)
45 if not buffered or buffered == 0 then
46 process.stdin:close()
47 write_fds[process.stdin] = nil
48 end
49 end
50 end
51 write(data_in or "")
52 local stdout_chunks, stderr_chunks = {}, {}
53 while next(read_fds) or next(write_fds) do
54 moonbridge_io.poll(read_fds, write_fds)
55 read(process.stdout, stdout_chunks)
56 read(process.stderr, stderr_chunks)
57 write()
58 end
59 return
60 table.concat(stdout_chunks),
61 table.concat(stderr_chunks),
62 process:wait()
63 end

Impressum / About Us