How to do a cleanup after SIGKILL?

2019-02-07 04:03发布

I'm working on a program which uses shared memory. Multiple instances of said program will either connect to an existing one or create it anew, and give it back to OS when there are no other processes or just detach it and terminate. I thought of using a simple counter to keep track of how many processes use it.

I'm using atexit() function to do the cleanup, however, afaik, upon receiving SIGKILL signal, processes won't do any cleanup, so if any of those processes don't terminate normally, I might never be able to clean the memory.

Is there a way to specify what to do even after a SIGKILL signal? I'm probably going to write some mechanism similar to a timer to check if processes are still alive, but I'd really like to avoid it if there is another way.

标签: c linux signals
3条回答
做自己的国王
2楼-- · 2019-02-07 04:14

No, SIGKILL cannot be caught in any way by your application - if it could, the application could ignore it, which would defeat its purpose.

查看更多
Bombasti
3楼-- · 2019-02-07 04:18

Combined with shared memory, robust mutexes located in the shared memory segment would be a great tool. If a process dies while holding a lock on a robust mutex, the next process to attempt locking it will get EOWNERDEAD and can perform the cleanup the original owner should have performed.

查看更多
神经病院院长
4楼-- · 2019-02-07 04:30

You can't catch SIGKILL.

However: you can still do cleanup, provided that cleanup is done by another process. There's lots of strategies you can go with here to let your housekeeping process see your other processes appear and disappear.

For example: you could have a Unix domain socket in a known location, which the housekeeper listens to; each slave process opens the socket to indicate it's using the shared memory segment. When a slave exits, for whatever reason, the socket will get closed. The housekeeper can see this happen and can do the cleanup.

查看更多
登录 后发表回答