[erlang-questions] spawn and controlling_process

Jachym Holecek <>
Mon Nov 3 10:30:26 CET 2014


# Gadi Srebnik 2014-11-01:
> How safe it is to use controlling_process after spawn? I am using
> additional gen_tcp:controlling_process inside the Mod:Fun itself after few
> additional commands. Is it possible that process will not be owner by then?

Yes, there's a race condition there, you need explicit synchronization to
be safe:

  start_worker(Sock) ->
      Pid = erlang:spawn(?MODULE, worker_init, [Sock]),
      gen_tcp:controlling_process(Sock, Pid),
      Pid ! proceed.

  worker_init(Sock) ->
      receive
          proceed ->
              %% Okay now we actually own it.
              worker_loop(Sock)
      after 1000 ->
          exit(things_seem_awfully_slow_today)
      end.
 
I wish there were a variant of controlling_process that would advise the
new owner automatically by sending {tcp_handover, Sock, Info} to it, the
last item being arbitrary term passed by previous owner. No idea how hard
would it be to implement.

BR,
	-- Jachym


More information about the erlang-questions mailing list