2

我正在尝试测试一些长生不老药代码,并遇到了一些我不理解的 gen_tcp 行为。当我 gen_tcp.accept 一个套接字时,我可以在我创建它的任务中“访问”它,但不是不同的。我认为这是一个“controlling_process”问题,但即使我添加任何尝试使用 :inet.getstat 都会导致无效参数错误。我也无法在套接字上接收,Elixir 声称它已关闭,但对于这个问题 getstat 更容易。见下文:

defmodule ElixirQuestion do
  def serve_one_client(socket, pid) 
  do  
    {:ok, server_socket} = :gen_tcp.accept(socket)
    :ok = :gen_tcp.controlling_process(server_socket, pid)
    IO.inspect(:inet.getstat(server_socket))
    server_socket 
  end 
end

{:ok, socket} = :gen_tcp.listen(0, [:binary, 
                                      {:packet, :raw}, 
                                      {:active, false}])
{:ok, port_number} = :inet.port(socket)
server_task = Task.async(fn -> ElixirQuestion.serve_one_client(socket, self()) end)
{:ok, _client_socket} = :gen_tcp.connect('localhost', port_number, [active: false]) 
server_socket = Task.await(server_task)

IO.inspect(:inet.getstat(server_socket))

预期产出

{:ok,
 [recv_oct: 0, recv_cnt: 0, recv_max: 0, recv_avg: 0, recv_dvi: 0, send_oct: 0,
  send_cnt: 0, send_max: 0, send_avg: 0, send_pend: 0]}
{:ok,
 [recv_oct: 0, recv_cnt: 0, recv_max: 0, recv_avg: 0, recv_dvi: 0, send_oct: 0,
  send_cnt: 0, send_max: 0, send_avg: 0, send_pend: 0]}

接收输出

{:ok,
 [recv_oct: 0, recv_cnt: 0, recv_max: 0, recv_avg: 0, recv_dvi: 0, send_oct: 0,
  send_cnt: 0, send_max: 0, send_avg: 0, send_pend: 0]}
{:error, :einval}

灵药版本

Erlang/OTP 19 [erts-8.3.5.3] [source] [64-bit] [smp:2:2] [async-threads:10] [hipe] [kernel-poll:false]

Elixir 1.4.5
4

1 回答 1

2

self()insideTask.async将返回Task进程的PID。由于您想要这里父进程的值,因此您需要将此值保存在传递给的 fn 之外Task.async,然后在内部使用它。

改变:

server_task = Task.async(fn -> ElixirQuestion.serve_one_client(socket, self()) end)

到:

me = self()
server_task = Task.async(fn -> ElixirQuestion.serve_one_client(socket, me) end)

给我你期望的输出:

{:ok,
 [recv_oct: 0, recv_cnt: 0, recv_max: 0, recv_avg: 0, recv_dvi: 0, send_oct: 0,
  send_cnt: 0, send_max: 0, send_avg: 0, send_pend: 0]}
{:ok,
 [recv_oct: 0, recv_cnt: 0, recv_max: 0, recv_avg: 0, recv_dvi: 0, send_oct: 0,
  send_cnt: 0, send_max: 0, send_avg: 0, send_pend: 0]}
于 2017-11-09T01:51:03.793 回答