1-module(sp). 2-vsn(2). 3 4-export([start/0, get_data/0, set_data/1]). 5-export([init/1, system_continue/3, system_terminate/4, 6 system_code_change/4]). 7 8-record(state, {data, last_pid}). 9 10start() -> 11 Pid = proc_lib:spawn_link(?MODULE, init, [self()]), 12 {ok, Pid}. 13 14get_data() -> 15 sp_server ! {self(), get_data}, 16 receive 17 {sp_server, Data} -> Data 18 end. 19 20set_data(Data) -> 21 sp_server ! {self(), set_data, Data}. 22 23init(Parent) -> 24 register(sp_server, self()), 25 process_flag(trap_exit, true), 26 loop(#state{last_pid = no_one}, Parent). 27 28loop(State, Parent) -> 29 receive 30 {system, From, Request} -> 31 sys:handle_system_msg(Request, From, Parent, 32 ?MODULE, [], State); 33 {'EXIT', Parent, Reason} -> 34 cleanup(State), 35 exit(Reason); 36 {From, get_data} -> 37 From ! {sp_server, State#state.data}, 38 loop(State, Parent); 39 {From, set_data, Data} -> 40 loop(State#state{data = Data, last_pid = From}, Parent); 41 _Any -> 42 loop(State, Parent) 43 end. 44 45cleanup(State) -> ok. 46 47%% Here are the sys call back functions 48system_continue(Parent, _, State) -> 49 loop(State, Parent). 50 51system_terminate(Reason, Parent, _, State) -> 52 cleanup(State), 53 exit(Reason). 54 55system_code_change({state, Data}, _Mod, 1, _Extra) -> 56 {ok, #state{data = Data, last_pid = no_one}}; 57system_code_change(#state{data = Data}, _Mod, {down, 1}, _Extra) -> 58 {ok, {state, Data}}. 59