Skip to content

Instantly share code, notes, and snippets.

@mietek
Created August 13, 2010 10:50
Show Gist options
  • Save mietek/522691 to your computer and use it in GitHub Desktop.
Save mietek/522691 to your computer and use it in GitHub Desktop.
-module(proc_lib_instance).
-export([start_link/0,
ping/1]).
-export([init/1,
system_continue/3,
system_code_change/4,
system_terminate/4]).
-record(st, {}).
-spec start_link() -> {ok, pid()} | {error, term()}.
start_link() ->
proc_lib:start_link(?MODULE, init, [self()]).
-spec ping(pid()) -> ok | {error, timeout}.
ping(Pid) ->
Pid ! {self(), ping},
receive
pong ->
ok
after 1000 ->
{error, timeout}
end.
-spec init(pid()) -> ok.
init(Parent) ->
proc_lib:init_ack(Parent, {ok, self()}),
Dbg = sys:debug_options([]),
St = #st{},
loop(Parent, Dbg, St).
-spec system_continue(pid(), list(), #st{}) -> ok.
system_continue(Parent, Dbg, St) ->
loop(Parent, Dbg, St).
-spec system_code_change(#st{}, atom(), term(), term()) -> {ok, #st{}}.
system_code_change(St, _Module, _OldVsn, _Extra) ->
{ok, St}.
-spec system_terminate(term(), pid(), list(), #st{}) -> none().
system_terminate(Reason, _Parent, _Dbg, _St) ->
exit(Reason).
-spec loop(pid(), list(), #st{}) -> ok.
loop(Parent, Dbg, St) ->
receive
{system, From, Msg} ->
sys:handle_system_msg(Msg, From, Parent, ?MODULE, Dbg, St);
{From, ping} ->
Dbg1 = sys:handle_debug(Dbg, fun format_debug/3, St, {in, {From, ping}}),
From ! pong,
Dbg2 = sys:handle_debug(Dbg1, fun format_debug/3, St, {out, pong}),
loop(Parent, Dbg2, St)
end.
-spec format_debug(term(), term(), #st{}) -> ok.
format_debug(Dev, Event, _St) ->
io:format(Dev, "*** ~p~n", [Event]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment