[erlang-questions] Print a message when a process dies

Harit Himanshu harit.subscriptions@REDACTED
Tue Jan 13 00:14:07 CET 2015


I need to make my own function my_spawn(M,F,A) which work similar to
spawn(M,F,A) but if a spawned process dies, I need to print a message
telling how long a process lived.


My attempt looks like

-export([my_spawn/3]).

my_spawn(Mod, Func, Args) ->
  Pid = spawn(Mod, Func, Args),
  Ref = monitor(process, Pid),
  Start = os:timestamp(),
  receive
    {'DOWN', Ref, process, Pid, _Why} ->
      io:format("process died after ~p microseconds.~n",
[timer:now_diff(os:timestamp(), Start)])
  end,
  Pid.


so when I run this, I see

1> Pid = error_handling:my_spawn(area_server1, area, []).
process died after 363 microseconds.

=ERROR REPORT==== 12-Jan-2015::15:06:53 ===
Error in process <0.33.0> with exit value:
{undef,[{area_server1,area,[],[]}]}

<0.33.0>
2>

*Problems**?*
- I am learning both Erlang and concurrency for the first time, so I see
following potential problems with this approach

a.) What if spawned process failed in the first place, so I get no Pid
b.) What if command fails executing either "Ref = .." or "Start = .."?

In such scenarios the program will not work effectively, what are the
recommended ways to solve such thing?

Also, do you see any potential race conditions here? I take a guess saying
no because even if multiple process trying to execute the same code, they
will return different Pid anyway, is that understanding correct?

Thanks a lot
+ Harit
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150112/4c7040a6/attachment.htm>


More information about the erlang-questions mailing list