[erlang-questions] Kill a process after T seconds

Hynek Vychodil vychodil.hynek@REDACTED
Wed Jan 21 11:47:16 CET 2015


I think the problem is you don't kill spawned process but parent. The code
should be
my_spawn(Mod, Func, Args, Time) ->
  Pid = spawn(Mod, Func, Args),
  io:format("created new process: ~p.~n", [Pid]),
  timer:kill_after(Time * 1000, Pid),
  Pid.

Note using timer:kill_after/2 instead of timer:kill_after/1

On Tue, Jan 13, 2015 at 7:55 PM, Harit Himanshu <
harit.subscriptions@REDACTED> wrote:

> The recent problem I worked on is
>
> Write a function my_spawn(Mod, Func, Args, Time) that behaves like
> spawn(Mod, Func, Args) but with one difference. If the spawned process
> lives for more than Time seconds, it should be killed.
>
> My attempt looks like
>
> my_spawn(Mod, Func, Args, Time) ->
>   Pid = spawn(Mod, Func, Args),
>   io:format("created new process: ~p.~n", [Pid]),
>   timer:kill_after(Time * 1000),
>   Pid.
>
> and when I run I see
>
> 1>  c(error_handling).
>
> {ok,error_handling}
>
> 2> Pid1 = error_handling:my_spawn(area_server0, loop, [], 30).
>
> created new process: <0.39.0>.
>
> <0.39.0>
>
> 3> Pid1 ! {self(), {square, 10}}.
>
> {<0.32.0>,{square,10}}
>
> 4> receive X->X end.
>
> 100
>
> 5> Pid1 ! {self(), {square, 20}}.
>
> {<0.32.0>,{square,20}}
>
> 6> receive Y->Y end.
>
> 400
>
> ** exception error: killed
>
> 7>
>
> Looking for suggestions on the code or ways to write it better
>
> Thanks
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150121/5ee5f0f8/attachment.htm>


More information about the erlang-questions mailing list