# Graceful interruption and ensure finishing current loop

**URL:** https://discourse.julialang.org/t/graceful-interruption-and-ensure-finishing-current-loop/92359
**Category:** General Usage
**Tags:** question, interruptexception
**Created:** [December 31, 2022, 1:30pm UTC](https://discourse.julialang.org/t/graceful-interruption-and-ensure-finishing-current-loop/92359 "2022-12-31T13:30:53Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![AllanChain](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/allanchain/32/45510_2.png) [@AllanChain](https://discourse.julialang.org/u/AllanChain)
#### Post date: [December 31, 2022, 1:30pm UTC](https://discourse.julialang.org/t/graceful-interruption-and-ensure-finishing-current-loop/92359/1 "2022-12-31T13:30:53Z")

</div>

I have a big for loop but each step only takes a few secs to finish. What I want is that when I press Ctrl+C, the program finishes the current loop and stores the states in a file.

I know there’s something called `exit_on_sigint(false)`, but it doesn’t seem to fit my needs, because the `InterruptException` could be thrown anywhere and the state is corrupted in the `catch` block. A minimal example:

```julia
function slow_sum()
    a=0 
    for i in 1:10
        try
            sleep(1)
            a+=i
        finally
            println("$a, $i") # store state
        end
    end
end

```

```julia
julia> slow_sum()
1, 1
3, 2
6, 3
^C6, 4
ERROR: InterruptException:

```

The final state is `6, 4` instead of `10, 4`, which is a problem. The real program is more complicated and many states are updated in many places.

In Python, we can do this (from [python - How to process SIGTERM signal gracefully? - Stack Overflow](https://stackoverflow.com/a/31464349/8810271))

```python
import signal
import time

class GracefulKiller:
  kill_now = False
  def __init__ (self):
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)

  def exit_gracefully(self, *args):
    self.kill_now = True

if __name__ == ' __main__':
  killer = GracefulKiller()
  while not killer.kill_now:
    time.sleep(1)
    print("doing something in a loop ...")
   
  print("End of the program. I was killed gracefully :)")

```

Is there anything equivalent to this in Julia?
