is it possible to resume the interrupted process after getting SIGTERM singal?

Viewed 73

In below program, What I am trying to achieve is when I press Ctrl+C or give SIGTERM then I want to make 'isEnable' false and let the while loop finish executing it's code one last time and exit the program gracefully. I can achieve this only with CancelKeyPress because EventArgs passed on this handler has Cancel property and I just need to set it true. And, CancelKeyPress only handle Ctrl+C. But, I want same thing when I got SIGTERM signal.

Does anyone know is it possible to resuming the process after getting SIGTERM signal just like in CancelKeyPress?

Please let me know if you need more information to understand my question.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            bool isEnable = true;

            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                isEnable = false; // making while loop false
                Console.WriteLine("Inside CancelKeyPress");
            };

            AppDomain.CurrentDomain.ProcessExit += (s, e) =>
            {
                isEnable = false;  // making while loop false
                Console.WriteLine("AppDomain ProcessExit!");
            };

            while (isEnable)
            {
                Console.WriteLine("first");
                Thread.Sleep(3000);
                Console.WriteLine("Second");
                Thread.Sleep(3000);
                Console.WriteLine("Third");
                Thread.Sleep(3000);
                Console.WriteLine("Fourth");
                Thread.Sleep(3000);
            }

            Console.WriteLine("Gracefull Shotdown");

        }
    }
1 Answers

SIGTERM is a "polite" way of asking the program to terminate gracefully.

The program can then handle this is any way it wishes.

  • It can ignore it
  • It can shut down immediately
  • It can finish processing the current task, then gracefully shutdown (disconnect from DB, close files etc).
  • It can wait as long as it wants and then shutdown.

(If running under Kubernetes then you can configure how long K8s will wait between sending a SIGTERM and a SIGKILL. So if your app needs 10 minutes to shut down then you can configure this and it is considered perfectly acceptable.)

In your code above, you are not "resuming processing" but are choosing to catch and handle this in your program by effectively ignoring the CTRL-C request.

So there is no reason why you can't do this also when receiving a SIGTERM on other platforms.

You might find this post helpful: https://medium.com/@rainer_8955/gracefully-shutdown-c-apps-2e9711215f6d

Related