Search code examples
clinuxsemaphoreshared-memoryfree

Semaphore cleanup in Linux c


When I create a shared memory (c program in Linux) I delete it with shmctl(shmid, IPC_RMID, 0) and everything looks fine when I'm using ipcs -m to check if there are any remaining shared memory segments. But I'm wondering how can I delete my semaphores that I've created right before the program is terminated because when I'm using ipcs -s I see both of my semaphores right there, result:

------ Semaphore Arrays --------
key        semid      owner      perms      nsems     
0x6b014021 0          benjamin   600        1         
0x6c014021 1          benjamin   600        1    

Thanks.


Solution

  • You can use semget and semctl after setting KEY to the right value returned by ipcs -s:

        #define KEY 0x...
    
        int id, rc;
    
        id = semget(KEY, 1, IPC_STAT);
        if (id < 0)
        {
            perror("semget"); 
            exit(1);
        }
    
        rc = semctl(id, 1, IPC_RMID); 
        if (rc < 0)
        {
            perror("semctl"); 
            exit(1);
        }
    

    Or use directly semctl with id returned by ipcs -s:

    rc = semctl(id, 1, IPC_RMID); 
    if (rc < 0)
    {
        perror("semctl"); 
        exit(1);
    }
    

    Full C program:

        #include <stdio.h>
        #include <stdlib.h>
        #include <unistd.h>
        #include <sys/types.h>
        #include <sys/sem.h>
        #include <errno.h>
    
        int main(int argc, char **argv){
    
                int id, rc;
    
                id = atoi(argv[1]);
    
                printf("id=%d\n", id);
                rc = semctl(id, 1, IPC_RMID); 
                if (rc < 0)
                {
                    perror("semctl"); 
                    exit(1);
                }
    
                exit(0);
            }
    

    Execution:

    $ ipcs -s
    
    ------ Tableaux de sémaphores --------
    clef       semid      propriétaire perms      nsems           
    0x00001111 393221     pifor      666        1         
    
    $ ./rsem 393221
    id=393221
    $ ipcs -s
    
    ------ Tableaux de sémaphores --------
    clef       semid      propriétaire perms      nsems