Skip to content

Commit 1d2c52a

Browse files
committed
Merge pull request elixir-lang#513 from glesica/controlling-process
Change controlling process in the gen_tcp tutorial
2 parents e29f2da + c1d7f96 commit 1d2c52a

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

getting-started/mix-otp/task-and-gen-tcp.markdown

+6-2
Original file line numberDiff line numberDiff line change
@@ -232,11 +232,14 @@ Now we just need to change `loop_acceptor/2` to use `Task.Supervisor` to serve e
232232
```elixir
233233
defp loop_acceptor(socket) do
234234
{:ok, client} = :gen_tcp.accept(socket)
235-
Task.Supervisor.start_child(KVServer.TaskSupervisor, fn -> serve(client) end)
235+
{:ok, pid} = Task.Supervisor.start_child(KVServer.TaskSupervisor, fn -> serve(client) end)
236+
:gen_tcp.controlling_process(client, pid)
236237
loop_acceptor(socket)
237238
end
238239
```
239240

241+
You might notice that we added a line, `:gen_tcp.controlling_process(client, pid)`. This makes the child process the "controlling process" of the `client` socket. If we didn't do this, the acceptor would bring down all the clients if it crashed because sockets are tied to the process that `accept`ed them by default.
242+
240243
Start a new server with `mix run --no-halt` and we can now open up many concurrent telnet clients. You will also notice that quitting a client does not bring the acceptor down. Excellent!
241244

242245
Here is the full echo server implementation, in a single module:
@@ -270,7 +273,8 @@ defmodule KVServer do
270273

271274
defp loop_acceptor(socket) do
272275
{:ok, client} = :gen_tcp.accept(socket)
273-
Task.Supervisor.start_child(KVServer.TaskSupervisor, fn -> serve(client) end)
276+
{:ok, pid} = Task.Supervisor.start_child(KVServer.TaskSupervisor, fn -> serve(client) end)
277+
:gen_tcp.controlling_process(client, pid)
274278
loop_acceptor(socket)
275279
end
276280

0 commit comments

Comments
 (0)