[erlang-questions] Strange Socket Behaviour (with spawn) Was:Parents always take children with them?

andrew cooke andrew@REDACTED
Sun Apr 29 14:30:52 CEST 2007

Thanks.  This is very embarrassing / frustrating, because I keep making
mistakes which obscure the "real" problem I am having (to me and everyone
else).  So I beg you patience, because I still have a problem (the same
problem that caused me to ask about parent processes, and the same problem
I have in more complex code, which these questions have tried to simplify
in (incorrect) examples).

The following code blocks on the socket read:

-define(BASE_TCP, [list, inet, {packet, raw}, {active, false}]).

start() ->
    {ok, A} = inet:getaddr("", inet),
    {ok, P} = gen_tcp:connect(A, 3128, ?BASE_TCP),
%    proc_lib:spawn(fun() ->
                  gen_tcp:controlling_process(P, self()),
                  io:format("blocking on ~p~n", [P]),
                  X = gen_tcp:recv(P, 0),
                  io:format("~p~n", [X]),
%          end)

However, if the comments are removed, the read returns {error, closed}
immediately.  This happens even if the socket is passed as an argument to
a separate function rather than implicitly via a closure, and closure is
delayed if the "parent" process time:sleep()s (The SASL output looks OK
now - thanks for that tip).

I have added the controlling_process call, since I thought that might be
the problem, but it makes no difference.  However, I am now thinking the
root cause is that the outer process "owns" the socket in some way and is
closing it.  Is that correct?  I suspect so - with the other error mistake
fixed (thanks) this is easier to reason about.

I really hope this is the last time I need to post about this.  Sorry
again for the confusion/mistakes.


> Ludovic Coquelle writes:
>  > ... so the normal behavior is that gen_recv doesn't block, which is
> probably
>  > intended since you request 0 byte with infinity timeout
> More precisely, gen_tcp:recv(P, 0) will block until at least one octet
> of data is available, with the options Andrew is using.
> But yes, Andrew's problem is as you diagnosed:  his "critical" line of
> code will crash the process because the second argument to io:format
> must be a list.
> Matthias

More information about the erlang-questions mailing list