Reputation: 163
I'm wondering if it's possible to have a child process continue normal operation until it receives a "die" message from a parent process.
Here's the child process's code.
-module(sensor).
-export([start/1]). % must also export function that will be spawned
%% create second thread, pass self() as argument so it knows how to reply
%% exchange messages with second thread until sum=0
start(SlaveNr) ->
%this part is not right. It waits for die and does nothing else
receive
die ->
io:format("slave ~p: received die~n", [SlaveNr])
end,
random:seed(now()),
Measurement = random:uniform(11),
if Measurement == 11 ->
exit(crash);
true->
io:fwrite("slave ~p Random # ~p~n",[SlaveNr, Measurement])
end,
Sleep_time = random:uniform(10000),
timer:sleep(Sleep_time),
start(SlaveNr).
As you can see, it's not executing normally. It's just waiting until it receives a die message. So how can I have it execute its normal function until it receives a die from the parent indicating all child processes should exit?
Upvotes: 0
Views: 110
Reputation: 14042
I understand that you want to check the mailbox at each loop, you can achieve this by adding a timout of 0 ms. So the process will check if any received message match to die, if not it will immediately continue.
receive
die ->
io:format("slave ~p: received die~n", [SlaveNr])
after 0 ->
ok
end,
It is always possible to stop a process using the exit/2
function: exit(Pid,Reason)
. In this case you do not have to add any code in your sensor module. If you use the atom normal
as Reason
, the process will die exactly as if is dying normally by itself.
Upvotes: 1