Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely close a large c application in linux?

I have large multi threaded c application , which basically does so many works, like local server, sql database communication, sip, and etc running on linux. I want to shutdown the linux machine, using "sudo shutdown -h now"

shall i close, my c application before shutting down system? what is the safe way to close my application.

If I close my application using "sudo kill -9 pID", then may be i loss some state of my application , my system may go into bad state.

For example: suppose i am reading and writing from a file in c, and shutdown commands come, what will happen? should I detect shutdown siganl from my code, and close file first then shutdown.? what is the right way?

Thanks

like image 895
Satya Sankar Avatar asked Nov 16 '25 05:11

Satya Sankar


1 Answers

The shutdown command initiates a shutdown procedure (traditionally by invoking init 0 but that might be no longer the case with systemd). This shutdown procedure consists roughly of the following parts:

  1. Disallow anyone from logging in
  2. Send a SIGTERM to all processes and wait a couple of seconds
  3. Send a SIGKILL to all processes and wait a couple of seconds
  4. Write all unwritten changes to disk
  5. turn off the system

If your program needs to react to a shutdown, the best way is to catch the SIGTERM the operating system sens you. When you get a SIGTERM, assume that someone wants you to terminate. Once you got a SIGTERM, write all changes to disk and safely shut down your application. Try not to make this process too complex as the system only gives you a limited time to react to a SIGTERM.

In general though, your program should deal with either itself or the system unexpectedly crashing. It should be written in a way that it can recover from a system crash with having inconsistent data structures. This is hard to get right and even a basic explanation of the strategies to do that would be too much for this answer.

like image 82
fuz Avatar answered Nov 18 '25 17:11

fuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!