ranch_acceptor.erl 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. %% Copyright (c) 2011-2014, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(ranch_acceptor).
  15. -export([start_link/3]).
  16. -export([loop/3]).
  17. -spec start_link(inet:socket(), module(), pid())
  18. -> {ok, pid()}.
  19. start_link(LSocket, Transport, ConnsSup) ->
  20. Pid = spawn_link(?MODULE, loop, [LSocket, Transport, ConnsSup]),
  21. {ok, Pid}.
  22. -spec loop(inet:socket(), module(), pid()) -> no_return().
  23. loop(LSocket, Transport, ConnsSup) ->
  24. _ = case Transport:accept(LSocket, infinity) of
  25. {ok, CSocket} ->
  26. Transport:controlling_process(CSocket, ConnsSup),
  27. %% This call will not return until process has been started
  28. %% AND we are below the maximum number of connections.
  29. ranch_conns_sup:start_protocol(ConnsSup, CSocket);
  30. %% Reduce the accept rate if we run out of file descriptors.
  31. %% We can't accept anymore anyway, so we might as well wait
  32. %% a little for the situation to resolve itself.
  33. {error, emfile} ->
  34. receive after 100 -> ok end;
  35. %% We want to crash if the listening socket got closed.
  36. {error, Reason} when Reason =/= closed ->
  37. ok
  38. end,
  39. flush(),
  40. ?MODULE:loop(LSocket, Transport, ConnsSup).
  41. flush() ->
  42. receive Msg ->
  43. error_logger:error_msg(
  44. "Ranch acceptor received unexpected message: ~p~n",
  45. [Msg]),
  46. flush()
  47. after 0 ->
  48. ok
  49. end.