Sungju's Slow Life

Personal journal


How to check who uses semaphore in the system

With ‘ipcs -s’ command we can see how many semaphores are existing and who created it, but sometimes, we wants to know who actually uses it.

Here’s a simple application you can check with semctl() function.

/* sem_pid.c */
#include 
#include 
#include 
#include 
#include 

int main(int argc, char **argv){
    if (argc < 2) {
        printf("Usage: %s n", argv[0]);
        return 1;
    }

    int semid = atoi(argv[1]);
    int pid = semctl(semid, 0, GETPID);
    if (pid < 0){
        printf("Error occurred while retrieving PIDn");
        return 3;
    }

    printf("%dn", pid);
    return 0;
}

http://pagead2.googlesyndication.com/pagead/show_ads.js

If you want to check all the semaphores on the system, you can use following simple script.

$ while read key semid owner perms nsems; do echo "Key: $key PID: $(./sem_pid $semid)"; done< <(ipcs -s | tail -n+4 | head -n-1)


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: