[erlang-questions] can a program launched with open_port({spawn, Cmd}, Options) remain running after the port closes?

Erik Søe Sørensen eriksoe@REDACTED
Thu Sep 27 14:37:31 CEST 2012


2012/9/27 Tim Watson <watson.timothy@REDACTED>

> Hi Erik,
>
> On 27 Sep 2012, at 03:20, Erik Søe Sørensen wrote:
>
> It is the responsibility of the port program to shut down when stdin
> reaches EOF.
> This behaviour/expectation confused me too at some point, but it probably
> has its merits: not all software is designed for "let it crash", so simply
> killing the port program might be too crude in some circumstances.
>
> Well that's fine, but it should be documented a bit more clearly IMHO.
>

It's not in the API docs for open_port(), but in the section in the manual
which definesports (
http://www.erlang.org/doc/reference_manual/ports.html#id84207) it does say

The external program resides in another OS process. By default, it should
read from standard input (file descriptor 0) and write to standard output
(file descriptor 1). *The external program should terminate when the port
is closed.*


> Also the port program, in this instance, is another beam emulator, so it's
> clearly *not* going to behave that way!
>
Why not? - see below.


> Currently the connected process for the port has 3 shutdown modes:
>
> 1. rpc:call(Node, custom_app, stop, [])
> 2. close_port(Port)
> 3. open_port({spawn, "kill -9 " ++ OsPid, Opts)
>

You could add
4. Ensure that the node runs a reading loop which detects EOF - e.g. using
file:read_line(standard_io) or file:read(standard_io, SomeBlockSize).

Example for detecting EOF:
erl -noshell -eval 'F=fun(G)->X=file:read_line(standard_io),
io:format("~p\n", [X]), X==eof orelse G(G) end, F(F), init:stop().'

You can even do exactly this in practise: put the loop code on the command
line.


>
> Item 3 is the least preferable as it is not portable (relies on 'kill'
> being a shell built-in, etc) and requires that the os process id is known.
> It sounds like (2) is not a workable solution unless the external program
> is hand written to deal with 'stdin reaches EOF'. This is less than ideal,
> as it means that open_port/2 is not much use for spawning (and monitoring
> thereafter) arbitrary programs unless you're willing to live with the fact
> that you're not able to shut them down by closing the port.
>

No, the port mechanism was apparently not meant for arbitrary slave
programs. However, a little wrapping can often get you far, as Jesper
demonstrated earlier.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20120927/22f8e7ec/attachment.htm>


More information about the erlang-questions mailing list