Squall
Squall

Reputation: 4472

How to automatically remove Unix IPC resources?

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

On Windows, when all handles are closed, the resource (semaphore or shared memory) is deleted by the system. However, Unix requires that I remove the resource, with shm_unlink (shared memory opened by shm_open) and sem_unlink (semaphore opened by sem_open). shm_open is good because it does not create real file in the disk.

I cannot use shmget because it requires a number as identifier instead of a string. ftok is completely useless because it may generate collisions.

I cannot call *_unlink before all handles be closed because it does not know when no new process will need it, and a process may crash or may be manually killed by the user.

If I do not unlink them, they will leave garbage in the system and if the process group be started again, they will not know whether the resources are being used by other processes or are old (it was not unlinked, the user killed the process or the process crashed).

Upvotes: 4

Views: 1034

Answers (1)

CoreyStup
CoreyStup

Reputation: 1488

AFAIK, theres no real portable way to handle auto-deleting SysV style IPC.

One option would be to create a supervisory daemon process, whos only task is to manage/own the shared mem/semaphore resources. A trick that works with some OS's is to have that process mark the shared memory as removed, which the OS will do upon all handles being closed. This isn't portable, as on some OS's new processes attempting to attach to a marked region will return EINVAL/EACCESS.

You could have your startup script clean up any orphaned resources to bring the system to known good state. Anything owned by your system uid would be a candidate for deleting through a "ipcs | xargs ipcrm" type of thing. Sure you're still orphaning things on failure/down, but who cares?

Upvotes: 1

Related Questions