C: Doing something when the program exits

风流意气都作罢 提交于 2019-12-05 02:42:04

look into the atexit API of the C standard library.

On POSIX, the proper solution is to protect the data with a robust mutex in shared memory. If your process has died with a robust mutex held, another program trying to lock the mutex will not deadlock but will instead return EOWNERDEAD, and then it has the opportunity to clean up the state protected by the mutex and call pthread_mutex_consistent.

Edit: If your only want to prevent multiple instances of the program from running, there are surely better/simpler ways, like holding a lock on the database file.

If your application terminates normally, it'll run functions registered through atexit. This is a standard function, available on Windows, unix and every other platform, and also in C++.

Note that “terminates normally” means through calls to exit() or by returning from main(). If your application terminates via abort() or _exit(), or if it is killed summarily from the outside, it may not have the opportunity to do any cleanup. There may be a better approach, possibly setting and clearing the flag in a wrapper program that does the cleanup regardless of how your program terminates, or dispensing with this flag altogether.

There are better ways of preventing the application to run twice. One solution is to use named mutexes that are system wide. Another and maybe simpler solution is to lock a file (open for writing). Even when the application crashes resources are freed by the OS and you will be able to start the application again, because the file or mutex will not be locked anymore.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!