Skip to content

Latest commit

 

History

History
71 lines (60 loc) · 1.9 KB

16.4.md

File metadata and controls

71 lines (60 loc) · 1.9 KB

16.4 プロセスの名前を付ける

OTPプロセスに一意でローカルな名前を付けられる サーバー開始時に :name オプションを使う :name オプションに使えるのは以下の4つ

  • nil
  • Atom
  • {:global, term}
  • {:via, module, term}
> {:ok, pid} = GenServer.start_link(Sequence.Server, 100, name: :seq)
{:ok, #PID<0.130.0>}
> GenServer.call(:seq, :next_number)
100
> GenServer.call(:seq, :next_number)
101
> :sys.get_status :seq
{:status, #PID<0.130.0>, {:module, :gen_server},
 [
   [
     "$initial_call": {Sequence.Server, :init, 1},
     "$ancestors": [#PID<0.128.0>, #PID<0.73.0>]
   ],
   :running,
   #PID<0.128.0>,
   [],
   [
     header: 'Status for generic server seq',
     data: [
       {'Status', :running},
       {'Parent', #PID<0.128.0>},
       {'Logged events', []}
     ],
     data: [{'State', "My current state is '102', and I'm happy"}]
   ]
 ]}

:name オプションに同じ値を指定するとエラーになる

> {:ok, pid2} = GenServer.start_link(Sequence.Server, 200, name: :seq)
** (MatchError) no match of right hand side value: {:error, {:already_started, #PID<0.130.0>}}
    (stdlib) erl_eval.erl:450: :erl_eval.expr/5
    (iex) lib/iex/evaluator.ex:249: IEx.Evaluator.handle_eval/5
    (iex) lib/iex/evaluator.ex:229: IEx.Evaluator.do_eval/3
    (iex) lib/iex/evaluator.ex:207: IEx.Evaluator.eval/3
    (iex) lib/iex/evaluator.ex:94: IEx.Evaluator.loop/1
    (iex) lib/iex/evaluator.ex:24: IEx.Evaluator.init/4
> {:ok, pid2} = GenServer.start_link(Sequence.Server, 200, name: :seq2)
{:ok, #PID<0.137.0>}

:name オプションに文字列を指定した場合

> {:ok, pid3} = GenServer.start_link(Sequence.Server, 200, name: "seq3")
** (ArgumentError) expected :name option to be one of the following:

  * nil
  * atom
  * {:global, term}
  * {:via, module, term}

Got: "seq3"

    (elixir) lib/gen_server.ex:845: GenServer.do_start/4