I am writing a simple app with 24 items in a hash to be persistent across program executions, so Berkeley DB (DBM) should be well suited for this task.
And it is just for fun.
But I wonder if using it (with Ruby), then when the user presses CTRL-C, then the execution is stopped. In this case, can't the data be all messed up?
For example, if the value in DB is 63, and I increment it by 1 (to be 64)
63 = 111111 (in binary)
64 = 1000000 (in binary)
so, could the CTRL-C occur right when the "Most Significant" 1 is written and but the 0s have not been written? In that case, the value in the DB will be 127 instead of 63 or 64. What if it is not Ruby but in C, and the user uses "close window" or "kill" to kill the process? Come to think about it, the hard drive probably write this byte (or 4-byte) to the hard disk surface all at once, so this shouldn't happen.
if CTRL-C won't cause this to happen, then a power outage or myself kicking the power plug could cause this to happen? For example, when the value is first cached in RAM, and while it is written to the hard disk, I kick the power plug, and the hard drive loses power before the 0s are written. I know one in a million times, this won't happen, but this is just a question of curiosity.
On the other hand, if my script is to
- Decrement the coin value
- Give the user a "hamburger" in his inventory
then when the user presses CTRL-C, and it happens right in between (1) and (2) above, then the user will have less coin, and get no hamburger.
To prevent all these from happening, it'd be to use the transactional method using SleepyCat, SQLite, or MySQL, and none of these will happen?