I have multiple apps compiled with g++, running in Ubuntu. I\'m using named semaphores to co-ordinate between different processes.
All works fine except in
If you use a named semaphore, then you can use an algorithm like the one used in lsof or fuser.
Take these in your consideration:
1.Each named POSIX semaphore creates a file in a tmpfs file system usually under the path:
/dev/shm/
2.Each process has a map_files in linux, under the path:
/proc/[PID]/map_files/
These map files, shows which part of a process memory map to what!
So using these steps, you can find whether the named semaphore is still opened by another process or not:
1- (Optional) Find the exact path of named semaphore (In case its not under /dev/shm)
Find the address location of the pointer in the memory (usually with a casting of the address of the pointer to in integer type) and convert it to hexadecimal (i.e result: 0xffff1234) number and then use this path:
/proc/self/map_files/ffff1234-*
there should be only one file that fulfills this criteria.
Get the symbolic link target of that file. It is the full path of the named semaphore.
2- Iterate over all processes to find a map file that its symbolic link taget matches the full path of the named semaphore. If there is one, then the semaphore is in real use, but if there is none, then you can safely unlink the named semaphore and reopen it again for your usage.
UPDATE
In step 2, when iterating over all processes, instead of iterating over all files in the folder map_file, it is beter to use the file /proc/[PID]/maps and search the full path of the named semaphore file (i.e: /dev/shm/sem_xyz) inside it.
In this approach, even if some other programs unlinked the named semaphore but the semaphore is still using in other processes, it still can be found but a flag of "(deleted)" is appended at the end of its file path.