[erlang-questions] gen_tcp:recv and hairloss, one resolution

Kevin q2h46uw02@REDACTED
Sun Nov 9 20:10:37 CET 2008

Hi all, thanks for all your good suggestions.

I guess I was still getting my threading legs when I fell for the bug of 
calling recv in two independent processes.  (I wasn't thinking
of a gen_fsm as a separate process.

In other words:

loop(Sock, Fsm) ->

    case gen_tcp:recv(Sock, 0TIMEOUT) of 
    {ok, Request} ->
          ok = gen_fsm:send_event(Fsm, {Request, Sock}), %% <--- calling recv again in here, do'h!
          loop(Sock, Fsm)
    {error, Reason} ->
            ok = gen_tcp:close(Sock),

My solution so far has been simply this:

loop(Sock, Fsm) ->
    ok = gen_fsm:sync_send_event(Fsm, Sock, infinity),
    loop(Sock, Fsm).

and then I call recv in each state function, which might sound messy but 
it looks pretty clean actually, and now
each state can decide how to handle streaming of data.

It solves the socket ownership problem also since sync_send_event must 
not be spawning a new process like
send_event does.

More information about the erlang-questions mailing list