/tags/yaws-0-42/yaws/src/yaws_ctl.erl

https://github.com/babo/yaws · Erlang · 109 lines · 75 code · 25 blank · 9 comment · 1 complexity · b5ee59f6232d39365c3b3dc49aed2bf4 MD5 · raw file

  1. %%%----------------------------------------------------------------------
  2. %%% File : yaws_ctl.erl
  3. %%% Author : Claes Wikstrom <klacke@bluetail.com>
  4. %%% Purpose :
  5. %%% Created : 29 Apr 2002 by Claes Wikstrom <klacke@bluetail.com>
  6. %%%----------------------------------------------------------------------
  7. %% some code to remoteley control a running yaws server
  8. -module(yaws_ctl).
  9. -author('klacke@bluetail.com').
  10. -compile(export_all).
  11. -include_lib("kernel/include/file.hrl").
  12. -define(F, "/tmp/yaws.ctl").
  13. start(_Top) ->
  14. case gen_tcp:listen(0, [{packet, 2},
  15. {active, false},
  16. binary,
  17. {ip, {127,0,0,1}},
  18. {reuseaddr, true}]) of
  19. {ok, L} ->
  20. case inet:sockname(L) of
  21. {ok, {_, Port}} ->
  22. F = ?F,
  23. file:write_file(F, io_lib:format("~w", [Port])),
  24. {ok, FI} = file:read_file_info(F),
  25. M = FI#file_info.mode,
  26. M2 = M bor (8#00222),
  27. file:write_file_info(F, FI#file_info{mode = M2}), %% ign ret
  28. aloop(L);
  29. _Err ->
  30. error_logger:format("Cannot get sockname for ctlsock",[])
  31. end;
  32. _Err ->
  33. error_logger:format("Cannot listen on ctl socket ",[])
  34. end.
  35. aloop(L) ->
  36. case gen_tcp:accept(L) of
  37. {ok, A} ->
  38. handle_a(A);
  39. _Err ->
  40. ignore
  41. end,
  42. aloop(L).
  43. handle_a(A) ->
  44. case gen_tcp:recv(A, 0) of
  45. {ok, Data} ->
  46. case binary_to_term(Data) of
  47. hup ->
  48. yaws:hup();
  49. stop ->
  50. init:stop();
  51. _Other ->
  52. ignore
  53. end,
  54. gen_tcp:close(A);
  55. _Err ->
  56. ignore
  57. end.
  58. actl(Term) ->
  59. case file:read_file(?F) of
  60. {ok, B} ->
  61. L = binary_to_list(B),
  62. I = list_to_integer(L),
  63. case gen_tcp:connect({127,0,0,1}, I,
  64. [{active, false},
  65. {reuseaddr, true},
  66. binary,
  67. {packet, 2}]) of
  68. {ok, Fd} ->
  69. gen_tcp:send(Fd, term_to_binary(Term)),
  70. gen_tcp:close(Fd);
  71. Err ->
  72. Err
  73. end;
  74. Err ->
  75. io:format("yaws: Cannot open runfile ~s ... server not running ?? ~n",
  76. [?F])
  77. end,
  78. init:stop().
  79. %% send a hup (kindof) to the yaws server to make it
  80. %% reload its configuration and clear its caches
  81. hup() ->
  82. actl(hup).
  83. stop() ->
  84. actl(stop).