# Running code when a script exits

**URL:** <https://forum.elixirforum.com/t/running-code-when-a-script-exits/32340>\
**Category:** Questions\
**Tags:** mix-run\
**Created:** [June 14, 2020, 6:08am UTC](https://forum.elixirforum.com/t/running-code-when-a-script-exits/32340 "2020-06-14T06:08:30Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![josevalim](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/josevalim/32/1787_2.png) [@josevalim](https://forum.elixirforum.com/u/josevalim)\
**Post date:** [June 16, 2020, 7:44am UTC](https://forum.elixirforum.com/t/running-code-when-a-script-exits/32340/14 "2020-06-16T07:44:35Z")

</div>

There are two questions here:

1. How to shut the system down cleanly

2. How to handle certain signals (interrupt)

To answer 1, `System.stop/1` is the answer. If `terminate/2` callbacks are not invoked, make sure those processes are trapping exits.

To answer 2, since Erlang/OTP 20, there is OS signal handling: [http://erlang.org/doc/man/kernel\_app.html#os-signal-event-handler](http://erlang.org/doc/man/kernel_app.html#os-signal-event-handler)

It is a bit of a long answer. In a nutshell, you need to implement a gen\_event handler and react to the callbacks you are interested. There is a more detailed guide here: [https://medium.com/@ellispritchard/graceful-shutdown-on-kubernetes-with-signals-erlang-otp-20-a22325e8ae98](https://medium.com/@ellispritchard/graceful-shutdown-on-kubernetes-with-signals-erlang-otp-20-a22325e8ae98)

---

_[View the full topic](https://forum.elixirforum.com/t/running-code-when-a-script-exits/32340)._
