Sometimes we need 'to return something to the system' when we finish a program, but it may be that the user 'killed the process' before the end of it without being expected.
Sometimes we need to return something to the system when we finish a program, but it may be that the user killed the process before the end of it without being expected.
It happens a lot in programs that have a loopwhile with tasks to be executed to the expected end!
Suppose you have this code that issues a warning at the beginning of the program and after 5 seconds the program ends and issues another warning:
After compiling and running, after 5 seconds these two messages appeared in the output:
Now suppose that before the end of 5 seconds, you press Ctrl + c, the second message will not appear and the output will be like this:
In other words, if your program has a function to be executed whenever the program ends, then it will generate a silent bug.
To solve this, we can map the signal sent and execute a certain task even if the program is interrupted before its normally expected end.
Using std::signal
First let’s include the header:
Create a callback function that will handle the signal, outside the execution of our class:
And start it in the constructor, or before the start of a supposed loop that we will execute!
The final code will be:
After compiling and running, after pressing Ctrl + c, the output will now be:
Note that after Ctrl + c(^C) the message appeared normally!
Another example without Object Orientation and with while