4

Similar to: Delete all shared memory and semaphores on Linux however, I want to do so in C, not with some script.

My specific problem: in linux + mac, when I debug a program and terminate it mid process, the shared resources (memory + semaphores) arent released. My program does some client server stuff where the server is the first process to acquire the shared resources. Therefore, after a termination without detaching, when I restart the program, it assumes that it is the client when there is no server (because the resource has been created and not released).

Currently, I am using Qt to manage the shared resources but Qt does not appear to have a way to deal with this situation (the error code that create returns is that the resource has already been created). Therefore, Im looking to a more OS specific way to do this. NOTE: windows does not have this problem because the shared resource is released on termination automatically.

Community
  • 1
  • 1
chacham15
  • 13,719
  • 26
  • 104
  • 207

1 Answers1

2

Check man ipcrm.

ipcrm - remove a message queue, semaphore set or shared memory id

Does the server terminate normally? If so you can have it call shmdt() before exiting. If it is crashing, then that's a little harder. One thing is to have it use shmctl to see how many processes have the shm attached. If it's 0, then you are obviously not the client.

There's also a flag you can set on shm segments IPC_RMID, although the usage seems a little ambiguous.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Chris J. Kiick
  • 1,487
  • 11
  • 14