Guarantee code execution even on process kill

前端 未结 4 635
太阳男子
太阳男子 2020-12-10 10:39

I need to execute a portion of code (the state save) on the process stopping - by itself, by user, by task manager, etc.

Is it possible?

try {} finally

4条回答
  •  萌比男神i
    2020-12-10 11:30

    You need to think about why your program is exiting. If it is because of an error, then you can use try/catch. In unix terms, what goes on when the process manager halts a process is a kill (i.e. sends a SIGKILL signal) which doesnt allow the program to do anything before the process is exited. What many viruses do is have two processes (possibly with shared memory to avoid constant data synchronization), each monitoring the state of the other and when one goes down, the other respawns it. Perhaps a second process could monitor and save the state in a similar way for your case. The other kind of signal though is a SIGTERM. This signal is sent when you tell your computer to restart but there are processes running. The kernel allows the programs to try and quit on their own, but eventually will ask the user if it is okay to kill the program. If you want to handle SIGTERM lookup handling signals. Ultimately the only solution that I know of to the SIGKILL is the two process solution.

提交回复
热议问题