Module test:
tester() ->
receive
X ->
erlang:display("message.."),
tester()
end.
initialize() ->
spawn_link(?MODULE, tester, []),
erlang:display("Started successfully.").
REPL:
length(erlang:processes()). -> 23
Pid = spawn_link(test, initialize, []).
length(erlang:processes()). -> 24
exit(Pid).
length(erlang:processes()). -> 24
It seems that the spawned tester process is still running! How do i make sure that when i exit my application, all spawn_link process are killed too?
Well, you are actually starting two Erlang processes, not one. The first one, to which you are sending the exit
signal, dies before you even send the exit signal, so the exit
has no effect.
The first process you start in the shell in this line:
Pid = spawn_link(test, initialize, []).
This process starts executing the initialize
function, in which it starts the second process, and then it dies because there is nothing else to do. This is the process to which you are trying to send the exit
signal.
To fix this simply return the correct Pid
from the initialize function:
initialize() ->
Pid = spawn_link(?MODULE, tester, []),
erlang:display("Started successfully."),
Pid.
And start it directly:
Pid2 = test:initialize().
Then you will be able to kill it with exit(Pid2).