emqttd_pmon.erl 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2013-2018 EMQ Enterprise, Inc. (http://emqtt.io)
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqttd_pmon).
  17. -author("Feng Lee <feng@emqtt.io>").
  18. -export([new/0, monitor/2, demonitor/2, erase/2]).
  19. -type(pmon() :: {?MODULE, map()}).
  20. -export_type([pmon/0]).
  21. new() ->
  22. {?MODULE, [maps:new()]}.
  23. -spec(monitor(pid(), pmon()) -> pmon()).
  24. monitor(Pid, PM = {?MODULE, [M]}) ->
  25. case maps:is_key(Pid, M) of
  26. true ->
  27. PM;
  28. false ->
  29. Ref = erlang:monitor(process, Pid),
  30. {?MODULE, [maps:put(Pid, Ref, M)]}
  31. end.
  32. -spec(demonitor(pid(), pmon()) -> pmon()).
  33. demonitor(Pid, PM = {?MODULE, [M]}) ->
  34. case maps:find(Pid, M) of
  35. {ok, Ref} ->
  36. erlang:demonitor(Ref, [flush]),
  37. {?MODULE, [maps:remove(Pid, M)]};
  38. error ->
  39. PM
  40. end.
  41. -spec(erase(pid(), pmon()) -> pmon()).
  42. erase(Pid, {?MODULE, [M]}) ->
  43. {?MODULE, [maps:remove(Pid, M)]}.