Search code examples
processerlangexiterlang-supervisorgen-server

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?


Solution

  • @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.