[erlang-questions] open_pipe({spawn, "cat"}) --- how to close stdin of cat?

173 views
Skip to first unread message

C K Tan

unread,
Mar 1, 2009, 4:45:53 AM3/1/09
to erlang-q...@erlang.org
Hi all,

I am tryinng to use port to open a program that reads until EOF from
stdin, and then write results to stdout ... i.e. something like the
unix wc command. I can't figure out how to close the stdin of the
spawned process:

wc(InputText) ->
P = open_port({spawn, "wc"}, [stream, exit_status, use_stdio,
stderr_to_stdout, in, out, eof]),
P ! {self(), {command, "hello world"}},
P ! {self(), {eof}}, %% ERROR -- how to close stdin of the cat process?
receive {P, X} -> X end.

Also, where can I find detailed documentation on open_port?

Appreciate any help.

Thanks,
-cktan
_______________________________________________
erlang-questions mailing list
erlang-q...@erlang.org
http://www.erlang.org/mailman/listinfo/erlang-questions

Michael Truog

unread,
Mar 1, 2009, 5:18:14 AM3/1/09
to C K Tan, erlang-q...@erlang.org
You normally never try to close stdin on the port. You can close stdin
on the port by calling erlang:port_close/1 but you won't be able to
receive on the port after you close it. You should be able to use a
read within the port program that does not depend on eof to terminate
the data (see http://erlang.org/doc/tutorial/part_frame.html by the
Ports section).

The documentation for erlang:open_port/2 is at
http://erlang.org/doc/man/erlang.html . The system commands without a
module name are within the erlang module. Consider using
erlang:port_command/2 rather than using ! directly, for better behavior.

- Michael

C K Tan

unread,
Mar 1, 2009, 5:48:36 AM3/1/09
to Michael Truog, erlang-q...@erlang.org
Michael,

Without closing stdin of wc, wc never returns because it thought there
are more data coming.

wc(InputText) ->
P = open_port({spawn, "wc"}, [stream, exit_status, use_stdio,
stderr_to_stdout, in, out, eof]),

port_command(P, InputText),
%% P ! {self(), {eof}}, %% ERROR -- how to close stdin of the wc process?
receive {P, X} -> X end,
port_close(P).


wc("hello world"). %% blocks forever.

Anthony Shipman

unread,
Mar 1, 2009, 8:49:28 AM3/1/09
to erlang-q...@erlang.org
On Sun, 1 Mar 2009 09:48:36 pm C K Tan wrote:
> Michael,
>
> Without closing stdin of wc, wc never returns because it thought there
> are more data coming.
>
> wc(InputText) ->
>    P = open_port({spawn, "wc"}, [stream, exit_status, use_stdio,
>                            stderr_to_stdout, in, out, eof]),
>    port_command(P, InputText),
>    %% P ! {self(), {eof}},   %% ERROR -- how to close stdin of the wc
> process? receive {P, X} -> X end,
>    port_close(P).

What I have done is use an intermediate shell script. I write EOF or some
similar marker to the port and the shell script closes the stdin for the
command it controls.

--
Anthony Shipman Mamas don't let your babies
a...@iinet.net.au grow up to be outsourced.

Reply all
Reply to author
Forward
0 new messages