Erlang Ports: Interfacing with a “wc”-like program

2020-03-04 02:48发布

I have an external exe program that reads from the stdin and produces a result. It works like the wc program and reads until the EOF. (Or End of Stream, rather.)

Update: let me add one more piece of explanation: I'm basically trying to write an Erlang pipe.

I'm able to call the program in a batch file like echo 339371249625 | LookupProj.exe but I want to be able to pass data to this from an Erlang gen_server.

I've looked at Erlang Ports but I'm having trouble getting them to play nice. Here's what I have:

test(InputText) -> 
   P = open_port({spawn, "/ExternEvent/LookupProj.exe"}, [stream, exit_status, use_stdio, 
                           stderr_to_stdout, in, out]),
   IBin = list_to_binary(InputText),
   %% io:format("~p~n",[I2]),
   P ! {self(), {command, <<IBin/binary, <<26>>/binary>>}}, %% ASCII 26 = EOF
   P ! {self(), {eof}},   %% ERROR -- how to close stdin of the cat process? 
   receive B -> io:format("~p",[B]) end.

I've tried using the eof flag in open_port to no help. (Not sure if this is the right flag?)

Where did I go wrong? Thanks!

标签: erlang cgi
1条回答
迷人小祖宗
2楼-- · 2020-03-04 03:32

If I understand correctly you are trying to re-use port connection between several calls like echo 339371249625 | LookupProj.exe, but afaik the only way to close the stdin is actually to close the port with port_close/1, so all this dance around ports is not any better than launching that commands with os:cmd/1.

If you can modify that LookupProj.exe you'd want to make consider some predefined byte sequence at stdin as an end of command and just send it each time you're done instead of EOF.

查看更多
登录 后发表回答