Removing Semaphores
Yes, you should call sem_remove()
when you are done with the semaphore set. Otherwise, the semaphore set will persist in the system until you remove it. However, the fact that the semaphore set persists causes no problem while the number of semaphores is less than the SEMMNS
limit:
SEMMNS
System-wide limit on the number of semaphores: policy dependent (on Linux, this limit can be read and modified via the second field of /proc/sys/kernel/sem
).
sem_remove()
immediately removes the semaphore set awakening all processes blocked using this semaphore.
By the way, you can use the ipcrm
command to remove semaphores from command line, and the ipcs
command to show information on IPC facilities (including semaphores).
Releasing Semaphores
You are not required to call sem_release()
while the auto-release flag (sem_get
's 4th parameter) is on. But it is a good idea to release semaphores as long as you don't need the acquired "lock".
sem_release()
only increments the value of internal semaphore. Think of it as an unlocking operation, the opposite of sem_acquire()
.
sem_get()
Failures
The sem_get()
function returns FALSE
in the following cases
- PHP parameter parsing failure (
E_ERROR
);
- semaphore exists, but the calling process does not have permission to access the set (
E_WARNING
);
- memory allocation error (
E_WARNING
);
- the maximum number of semaphore sets, or the system wide maximum number of semaphores exceeds (
E_WARNING
)
In each of the cases sem_get
logs an error, or a warning. So you have to check the logs in order to find out the root of the problem.
Since your code works for some time, it is not parameter parsing issue, and not the permissions. Memory allocation issues are rare. So it is very likely that you are running out of the semaphore number limits. Check out the man page for semget
for reference. The man page describes how to read and modify the limits via /proc/sys/kernel/sem
.
Refer to this answer for more information regarding the sysvsem
extension internals.