RAII and system resource cleanup

2019-07-23 15:56发布

问题:

RAII is a good solution for resource cleanup. However, RAII is based on stack unwinding. If process terminates abnormally, the stack won't be unwinded. It means RAII won't work in this situation. For process life-time's resource, it's nothing to worry about, but for file system life tiem or kernal life time resource, such as file, message queue, semaphore, shared memory, it will be a problem.

How can I cleanup the system(fs and kernal) resource in a reliable way?

Example: A shared file will be create by "master" process, and be used by "slave" process. The shared file should be deleted by "master" process in plan. Does it exist a way to do that.

Obvious, the shared file can't be unlink at once after it is created. If that, other processes can't "see" the file.

回答1:

There is no perfect answer to your question. You mostly just mitigate the effects as best you can, so that "abnormal termination leaving junk behind" is rare.

First, write your programs to be as robust as possible against abnormal process termination.

Second, rely on kernel mechanisms where possible. In your shared file example, if you are just talking about one "master" and one "slave" process using a file to communicate, then you can unlink the file as soon as both processes have it open. The file will continue to exist and be readable and writable by both processes until both of them close it, at which point the kernel will automatically reclaim the storage. (Even if both of them terminate abnormally.)

And of course, the next time your server starts, it can clean up any junk left by the previous run, assuming only one is supposed to exist at a time.

The usual last-chance mechanism is to have "cleanup" processes that run periodically to (e.g.) sweep out /tmp.

But what you are asking is fundamentally hard. Any process responsible for handling another's abnormal termination might itself terminate abnormally. "Who watches the watchers?"