Stratus3D
Stratus3D

Reputation: 4906

Erlang alternative to trap_exit?

I would like to execute some code when my gen_server is stopped. I have my gen_server trapping exits (I added process_flag(trap_exit, true) to the init callback). This works well as terminate/2 is always called before the process exits. I know that since I am trapping exits linked processes that crash do not crash the gen_server I created. I could work around this but I am wondering if there is an alternative to using process_flag(trap_exit, true) to achieve this?

I just want a "before the process exits" callback. Does something else like this exit?

Upvotes: 1

Views: 387

Answers (2)

tkowal
tkowal

Reputation: 9289

@Pascal's answer is perfectly right, but I would like to propose another aproach.

Sometimes you want to spawn processes by the gen_server, but usually, you can put them in the supervision hierarchy, which is much safer. You can have those processes and gen_server spawned by the same supervisor with one_for_all restart strategy. If one of the processes dies, they all get restarted. Secondly you have to specify timeout for shutdown strategy - this will ensure, that the terminate function will be called.

Upvotes: 2

Pascal
Pascal

Reputation: 14042

Fron doc:

When trap_exit is set to true, exit signals arriving to a process are converted to {'EXIT', From, Reason} messages, which can be received as ordinary messages. If trap_exit is set to false, the process exits if it receives an exit signal other than normal and the exit signal is propagated to its linked processes. Application processes should normally not trap exits.

This means that the process which has is trap_exit flag set to true will not exit if any of its linked processes die abnormally. It must have a receive block with a clause to catch any message of the form {'EXIT', From, Reason}. In this receive clause you can do what you need before eventually stopping your process.

in a gen_server you will have to write a callback Module:handle_info({'EXIT', From, Reason}, State) -> Result.

Upvotes: 4

Related Questions