How to automatically remove Unix IPC resources?

I need to port some applications from Windows to Linux, and they use shared memory and semaphores. I have to replace some Winddows functions like CreateFileMapping / OpenFileMapping and CreateSemaphore / OpenSemaphore. I will write a common interface for semaphore and shared memory later.

On Windows, when all descriptors are closed, the resource (semaphore or shared memory) is deleted by the system. However, Unix requires me to delete the resource, with shm_unlink (shared memory, open shm_open) and sem_unlink (semaphore, open sem_open). shm_open is good because it does not create a real file on disk.

I cannot use shmget because a string requires a number as an identifier. ftok is completely useless as it can generate collisions.

I cannot call * _unlink before all descriptors are closed, because it does not know when a new process is not needed, and the process may crash or it may be manually killed by the user.

If I do not disconnect them, they will leave garbage in the system, and if the process group is started again, they will not know if the resources are used by other processes or are old (this was not disconnected, the user killed the process or the process crashed).

+4
source share
1 answer

AFAIK, there is no real portable way to handle the automatic removal of SysV-style IP addresses.

One option is to create a dispatch daemon process whose task is only to manage / own shared resources mem / semaphore. The trick that works with some OSs is for this process to mark shared memory as remote, which the OS will do when all descriptors are closed. This is not portable, since on some operating systems new processes trying to connect to the marked area will return EINVAL / EACCESS.

You may have your startup script clear any lost resources to bring the system to a good state. Anything that belongs to your uid system would be a candidate for removing the type "ipcs | xargs ipcrm". Of course, you are still an orphan to failure / down, but who needs it?

+1
source

Source: https://habr.com/ru/post/1393569/


All Articles