Semaphore

Here, I don't provide the theoretical concept of semaphore. This lesson only for fun and I believe that you will learn basic terms of semaphore.

Semaphore is one kind of variable. Well! what type variable of is it? It is a integer type variable. And it is global, so any process can access it.

Like other integer variable you need to initialize it. We can define an integer variable like below:

int i;
i=3;

printf(" %d", i);   // to show the value of variable.

You also can do similar process in semaphore but in a different way. Yes, There is some functions to define semaphore variable.

semget( ):
semid = semget(key, nsems, semflg)
 
where, semid is integer, key is hex number(address), nsems is number of semaphore, semflg  is flag. The name of your variable is now semid. You can access it using semid.
Now, how will I put value in it ? Okay, there is another function.

Semctl( ):
int semctl(int semid, int semnum, int cmd, union semun arg);

semid is the value that you get from previous function. senum is the number of semaphore variable index, cmd is very important. It says what we to do in segctl ( ). And, arg takes the value of semaphore variable.

There are different types of cmd for semctl().
SETVAL -- to put value in a single semaphore. 
GETVAL -- to get value of a semaphore.
 
SETALL -- to put all value of semaphore.  

GETALL -- to get value of all semaphore.
 

GETPID -- get PID of process 
 
There is another function that is described on next lesson:
semop(int semid, struct sembuf *buf,  int nsops);

There is one example:
//   Write " ipcs -s "  in Terminal to see semaphore list 
  
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/sem.h> 
#include <error.h> 

int main()
{
 int ret_value= 0;
 
 key_t key= 0x20 ;  // key to pass to semget()  
 int nsems = 1 ;   // the number of elements in a semaphore array  
 int semflg= 0666 | IPC_CREAT ; // initial access permissions 
 int semid;        /* return value from semget() */ 

 if( ( semid = semget( key , nsems, semflg ) ) == -1) {
      perror("semget: semget failed"); 
      exit(1);
   } 
 printf(" The id is %d\n", semid);
 semctl ( semid, 0, SETVAL, 7 );               //   set value
 ret_value = semctl ( semid, 0, GETVAL, 0 );   //   get value
 printf(" value is %d\n", ret_value);
 
 return 0;
}

///  code collect from : Odyssey Book
 

 Hope, you like it. Go at next post




মন্তব্যসমূহ

একটি মন্তব্য পোস্ট করুন