pandoragami
pandoragami

Reputation: 5575

Erlang: When does a process terminate and how does gen_tcp:controlling_process(Socket, Pid) work?

What I want to know is whether a process Pid gets terminated when the socket closes if the controlling process is created using gen_tcp:controlling_process(Socket, Pid), and also under what conditions does the socket send this message {tcp_closed, Socket}? Is there a way to prevent the socket on the server side from closing, or is that always normal? Also is there any specific way to terminate a process knowing the Pid?

Upvotes: 1

Views: 494

Answers (1)

Pascal
Pascal

Reputation: 14042

gen_tcp:controlling_process(Socket, Pid) is used to give the control of a Socket to the process Pid. It implies nothing about the behavior of this process when the Socket is closed.

There are to cases to consider:

  • You open the server Socket in the mode {active,false} in this case the server will know that the Socket is closed when it calls the function gen_tcp:recv(Sock, Len) getting the answer {error, closed} instead of the expected {ok, Binary}. I recommend you to use this mode if you intend to use gen_tcp:controlling_process(Socket, Pid) because it allow you to avoid a race condition in your code.

  • You open the server Socket in the mode {active,true} or {active,once}, in this case, the server will receive a message {tcp_closed, Socket}. In this case, there is a race condition see topic Erlang: Avoiding race condition with gen_tcp:controlling_process

I don't think it is the role of the server to prevent any Socket to close, but rather to always be ready to accept a connection.

Last it is always possible to terminate a process, using your own protocol for a smooth end for example Pid ! {stop,Reason} or a more brutal way using exit(Pid, Reason).

Upvotes: 5

Related Questions