Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semaphores remain open after application exits

I have a 3rd party application written in C for Linux platform. The application creates semaphores using below code:

union semun {
    int Value;
    struct semid_ds *Buffer;
    unsigned short * Array;
} Arg;

Arg.Value = 0;

SemId = semget(IPC_PRIVATE , ONE_SEMAPHORE, 0666 | IPC_CREAT);

semctl(SemId, 0, SETVAL, Arg);

When the application exits, these semaphores are deleted by the application using below code:

semctl(SemId, 0, IPC_RMID);

If the application is stopped abnormally (such as by sending multiple SIGINT signals), these semaphores remain open. These semaphores can be seen open by using below command:

ipcs -s

These semaphores have to be removed from the system manually by using ipcrm command.

How can I ensure that the semaphores created by the application get deleted when the application finally exits? I have read that exit() call closes all open named semaphores. However these are not named semaphores.

I thank you in advance for your help.

like image 242
geekowl Avatar asked Feb 20 '23 23:02

geekowl


1 Answers

For handling Abnormal terminations we can install the signal handlers

/* signal handlers available in signal.h */
#include <signal.h>

void SignalHandler(int iSignalNum)
{
    switch(iSignalNum)
    {
    case SIGINT:
    case SIGSEGV:
    case SIGTSTP:
        {
           /* Add Stuffs if necessary */
           semctl(SemId, 0, IPC_RMID);
        }
     break;
     default:
        break;
    }
   exit(0); 
}        


int main()
{
        ....

        /* Register the signal handlers */
        signal(SIGINT,  SignalHandler);
        signal(SIGSEGV, SignalHandler);
        signal(SIGTSTP, SignalHandler);
        .....
}
like image 52
Jeyaram Avatar answered Feb 27 '23 18:02

Jeyaram