next up previous contents
Next: Pamięć dzielona Up: Semafory Previous: Źródło   Contents

semstat: kompan programu semtool

Jako dodatek: kod źródłowy programu semstat. Jest to program wyświetlający wartości każdego semaforu z zestawu utworzonego za pomocą semtool.


   /*****************************************************************************
    Zaczerpnięto z "Linux Programmer's Guide - Rozdział 6"
    (C)opyright 1994-1995, Scott Burkett
    ***************************************************************************** 
    MODUŁ: semstat.c
    *****************************************************************************
    Program towarzyszący semtool. semstat wyświetla wartości semaforów z zestawu
    utworzonego przez semtool.
    *****************************************************************************/
   
   #include <stdio.h>
   #include <stdlib.h>
   
   #include <sys/types.h>
   #include <sys/ipc.h>
   #include <sys/sem.h>
   
   /* U mnie ( RedHat6.0, jądro 2.2.12-20 )
   #include <sys/types.h>
   #include <sys/ipc.h>
   #include <sys/sem.h>    */
   
   
   int get_sem_count(int sid);
   void show_sem_usage(int sid);
   int get_sem_count(int sid);
   void dispval(int sid);
   
   int main(int argc, char *argv[])
   {
           key_t key;
           int   semset_id;
   
           /* tworzymy unikalny klucz za pomocą wywołania ftok() */
           key = ftok(".", 's');
   
           /* otwieramy zestaw semaforów - nie tworzymy! */
           if((semset_id = semget(key, 1, 0666)) == -1) 
           {
                   printf("Zestaw semaforów nie istnieje\n");
                   exit(1);
           }
   
           show_sem_usage(semset_id); 
           return(0);
   }
   
   void show_sem_usage(int sid)
   {
           int cntr=0, maxsems, semval;
   
           maxsems = get_sem_count(sid);
   
           while(cntr < maxsems) {
                   semval = semctl(sid, cntr, GETVAL, 0);
                   printf("Semafor#%d:  --> %d\n", cntr, semval);
   cntr++;
           }
   }
   
   int get_sem_count(int sid)
   {
           int rc;
           struct semid_ds mysemds;
           union semun semopts;
   
           /* pobierz wartości wewnętrznej struktury danych */
           semopts.buf = &mysemds;
   
           if((rc = semctl(sid, 0, IPC_STAT, semopts)) == -1) {
                   perror("semctl");
                   exit(1);
           }
   
           /* zwróć liczbę semaforów w zestawie */
           return(semopts.buf->sem_nsems);
   }
   
   void dispval(int sid)
   {
           int semval;
   
           semval = semctl(sid, 0, GETVAL, 0);
           printf("semval = %d\n", semval);
   }
   




2000-03-01


Poltronic