0
votes

If I create a module with this code below

start_nonstop() ->
  spawn(fun() ->
        Pid = spawn(?MODULE, nonstop, [0]),
        timer:sleep(1000),
        exit(Pid, kill)
    end).

nonstop(N) ->
    io:format("number: ~B~n", [N + 1]),
    nonstop(N + 1).

and call start_nonstop() from the Erlang shell, I see an endless series of

number: 1

number: 2

...

which means that the nonstop(N) process was not killed as expected by calling exit(Pid,kill)...

What am I doing wrong? Obviously, this code is a mockup, but I think there is always the chance that some logic bug in a process might result in an infinite loop behaviour similar to this one.

I supposed this could be handled by Erlang, but if not, how can I have an Erlang application be protected regarding these kind of situations?

Which patterns of "infinite loops" can Erlang break? For example, if I put a sleep in the middle of the nonstop(N) functions, Erlang can break the infinite loop, but if I put an erlang:yield() it still cannot break from the infinite loop ...

In this case the infinite process is local to the one trying to kill it. But, what if the infinite process was in a different (e.g., remote) Erlang VM? Could it be killed then?

I am a newbie, and I am evaluating Erlang before I put too much effort in learning and using it for serious applications.

Thanks

1
I am having trouble now with this thread because I am not seeing the answers or comments that other people have already made (which I could see some minutes ago). Can someone help? - mljrg
Please see my answer. - BlackMamba

1 Answers

1
votes

In this code, you spawn two process. In function start_nonstop(), you spawn an process, we can call it Process1. Then in Process1, you spawn another process, we call it Process2.

The work of Process2 is:

nonstop(N) ->
    io:format("number: ~B~n", [N + 1]),
    nonstop(N + 1).

just do io:format("number: ~B~n", [N + 1]), until the Process1 kill it.

In my environment, the Process2 can be killed. But the variable N become very large from the output.

number: 51321
number: 51322
number: 51323
number: 51324
number: 51325
number: 51326
number: 51327
number: 51328
number: 51329
number: 51330
number: 51331
number: 51332
7>