[newbie] accept()-ing process under supervision (was:Erlangish way of Iterator pattern)

Vance Shipley vances@REDACTED
Wed Jan 26 18:16:51 CET 2005


On Wed, Jan 26, 2005 at 04:07:29PM +0100, Joe Armstrong (AL/EAB) wrote:
}  
}  [almost] - the code above is incorrect - and is merely to illustrate the idea -
}  why is it incorrect? (ten brownie points for the first correct explanation of the error :-)

I'm not sure what you're looking for.  Mainly the fun to handle
the exit reason is being called with Reason only but expects the
full {'EXIT', Pid, Reason} message.  Other wise, with some syntax
corrections, it seems to work:

1> brownie:keep_alive(fun() -> receive abort -> exit(abort) end end).
<0.32.0>

2>  i().
...
<0.31.0>              erlang:apply/2                         233 15    0
                      erl_eval:receive_clauses/6               8              
<0.32.0>              erlang:apply/2                         233 4    0
                      brownie:'-on_exit/2-fun-0-'/2            3              

3> P = list_to_pid("<0.31.0>").
<0.31.0>

4> P ! abort.
abort

5> i().
...
<0.36.0>              erlang:apply/2                         233 15    0
                      erl_eval:receive_clauses/6               8              
<0.37.0>              erlang:apply/2                         233 4    0
                      brownie:'-on_exit/2-fun-0-'/2            3              

Although I'd say the main problem is that since it doesn't spawn_link
it is possible for the process to exit before the link takes place.

	-Vance


-------------- next part --------------
-module(brownie).
-export([keep_alive/1]).

on_exit(Pid, Fun) ->
	spawn(fun() ->
				process_flag(trap_exit, true),
				link(Pid),
				receive
					{'EXIT', Pid, Why} ->
						Fun(Why)
				end
			end).

keep_alive(Fun) ->
	Pid = spawn(Fun),
	on_exit(Pid,
			fun(normal) ->
					true;
				(_Other) ->
					%% restart it
					keep_alive(Fun)
			end).



More information about the erlang-questions mailing list