gen_server 在子进程停止时停止不匹配

gen_server stop badmatch on sub process stopped

我有一个 table 进程,它为 board 创建一个 pid 作为其状态的一部分 go()

我正在测试终止 table 也会终止电路板。但是董事会并没有像预期的那样停止。

我的测试:

kills_board_test() ->
  {ok, Table} = table:go(),
  {BoardPid, _ ,_ } = s:s(Table, info),
  gen_server:stop(Table),
  undefined = process_info(BoardPid).

table.erl我实现:

handle_call(stop, _From, State = {Board, _, _}) ->
    gen_server:stop(Board),
    {stop, normal, shutdown_ok, State};

我的结果是:

> 6>table_test:test(). table_test: kills_board_test (module
> 'table_test')...*failed* in function table_test:kills_board_test/0
> (table_test.erl, line 8)
> **error:{badmatch,[{current_function,{gen_server,loop,6}},
>            {initial_call,{proc_lib,init_p,5}},
>            {status,waiting},
>            {message_queue_len,0},
>            {messages,[]},
>            {links,[]},
>            {dictionary,[{'$initial_call',{board,init,1}},
>                         {'$ancestors',[<0.351.0>,<0.349.0>]}]},
>            {trap_exit,false},
>            {error_handler,error_handler},
>            {priority,normal},
>            {group_leader,<0.350.0>},
>            {total_heap_size,233},
>            {heap_size,233},
>            {stack_size,9},
>            {reductions,152},
>            {garbage_collection,...},
>            {...}]}   output:<<"Table Terminating.{<0.352.0>,
>                    #{current_player => x,result => playing},
>                    #{o => {<0.355.0>,<0.356.0>},x => {<0.353.0>,<0.354.0>}}} ">>
> 
> =======================================================   Failed: 1.  Skipped: 0.  Passed: 0. error 

编辑:

我看到了文字 "terminating",但我知道 stop 会等待终止完成后再返回。

您的自定义停止行为在 handle_call(stop, ...) 中,但您调用的 gen_server:stop/1 不会调用该代码。您可能打算改为 gen_server:call(Table, stop)

也就是说,您可能希望将此停止行为移动到 Module:terminate/2 是由 gen_server:stop 自动调用的 (除非您有理由这样做在 handle_call):

中实现此行为
terminate(_Reason, _State = {Board, _, _}) ->
  gen_server:stop(Board)

现在,gen_server:stop(Table) 将调用此回调并自动停止 Board