Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle getting killed (kill -9) while using Shared Memory?

I am using Shared Memory in a Client-Server Model. When my Server gets killed off by the user by using sigkill instead of sigterm / sigint I can't do anything about it (as intended), but my Shared Memory Object and Semaphores still exist in /dev/shm/.

The next time I start my Server I want to create a new object with exactly the same name, and - as intented - this fails and I exit my program.

The user would need to remove the objects on his own - which is certainly not the best thing.

How can I handle this?

I could just call shm_open() without the O_EXCL flag, ultimately destroying the purpose of this flag. Because maybe there is already an instance of my server running and uses this object.

Pulseaudio seems to use a combination of digits to keep it's objects distinct and doesn't get affected by killing it with -9, so there seems to be a way.

like image 549
Haini Avatar asked Jan 10 '16 17:01

Haini


1 Answers

One option is to use IPC_RMID (see this).

This options marks the shm segment for cleanup after the last process attached to it disappears.

For semaphores, you can look at robust mutexes. It does require you to code for an extra error case (when a process holding the mutex dies).

You also have the option of using file locks, which are released if the process terminates (see lockf()).

like image 69
Ziffusion Avatar answered Nov 15 '22 03:11

Ziffusion