Erlang/OTP Forums

Author Message

<  Open Telecom Platform (OTP)  ~  spawn inside gen_server

5hundy
Posted: Sat Oct 11, 2008 9:41 am Reply with quote
User Joined: 14 Oct 2007 Posts: 17
Lets imagine I have the following gen_server code sans boilerplate:

Code:
start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
stop() -> gen_server:cast(?SERVER, stop).

init([]) ->
    process_flag(trap_exit, true),
    spawn_link(fun() -> say_hello() end),
    {ok, []}.

say_hello() ->
    io:format("hello world!~n"),
    timer:sleep(2000),
    say_hello().


1) How can I ensure that the say_hello loop will die if the server stops or crashes?

2) How can I either kill the server or at least alert it if the say_hello loop stops or crashes?
View user's profile Send private message
Mazen
Posted: Sat Oct 11, 2008 12:49 pm Reply with quote
User Joined: 20 Jul 2006 Posts: 164 Location: London
1) Link it to the process that spawned it (requires you to send the pid of the process that is spawning the process). This will kill a process if it is linked to the process that crashed. See reference manual chapter 10.6 [1].

2) using process_flag(trap_exit) will give you an info message when/if a process crashes[2].

See:
[1]: http://www.erlang.org/doc/reference_manual/processes.html#10.6
[2]: http://www.erlang.org/doc/man/erlang.html#process_flag-2
View user's profile Send private message
5hundy
Posted: Mon Oct 13, 2008 9:37 pm Reply with quote
User Joined: 14 Oct 2007 Posts: 17
Thanks for the help! For now I've decided to completely bring down the server if the loop fails, and bring down the loop if the server fails. From the example above I stopped trapping exits in the init and I pass the loop PID around in the State variable. In the terminate callback I just tell the loop to shutdown.
View user's profile Send private message
Mazen
Posted: Tue Oct 14, 2008 7:58 am Reply with quote
User Joined: 20 Jul 2006 Posts: 164 Location: London
Have you had a look at the supervisor behaviour? I might be what you are trying to achieve...

/Mazen
View user's profile Send private message
5hundy
Posted: Wed Oct 15, 2008 6:33 am Reply with quote
User Joined: 14 Oct 2007 Posts: 17
Yeah that's what I'm doing in the actual project I'm working on. Having the loop or the server fail for some reason should be rare so I figure the supervisor can just restart it.
View user's profile Send private message

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You can attach files in this forum
You can download files in this forum