[erlang-questions] Unidirectional linking?

Igor Ribeiro Sucupira <>
Wed May 25 08:00:45 CEST 2011


Suppose there is a heavy operation Op that in some cases takes so long
to finish that the caller loses interest in the result and gives up.

I want to perform that operation in a way that allows me to:
1) Interrupt its execution if it does not finish in N milliseconds.
2) Interrupt its execution if the calling process exits (here I'm
already supposing Op has to be run in another Erlang process, due to
goal 1).

To implement that, it seems unidirectional linking would be needed. Is
there another safe and convenient way to do it?

The first idea I had was something like this:

Parent = self(),
Child = spawn_link(fun() -> Parent ! (catch Op) end),
receive Result -> Result
after N -> unlink(Child), exit(Child, timeout), timeout
end.

But, if Parent is killed by another process right after calling
unlink, Child would be left executing.
Another problem is that I don't want Parent to die if Child exits for
non-timeout reasons (although it seems very unlikely in the code
above, with the catch).

I was now thinking of substituting unlink(Child) with
process_flag(trap_exit, true) and then kill Child, receive its exit
message, set trap_exit to false again (I'm assuming it was false), and
finally check if there were other exit messages (suiciding if it was
the case).

But then the code would become too ugly, so I got lazy and decided to
post to this list.  :-)

What do you think?

Thanks.
Igor.



More information about the erlang-questions mailing list