Semaphore 2

Please, read the previous lesson first.

Suppose, we want to access one semaphore variable in two process. So what to do? There are two programs that will use same semaphore variable. In first program, we will set or keep a value. And In next code, we take the value and print it.

First.cpp
----------------------------------------------------------------
#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()
{
    key_t key= 0x20 ;        
    int nsems = 1 ;                                              // making one semaphore variable
    int semflg= 0666 | IPC_CREAT ;  
    int semid;                            

    semid = semget( key , nsems, semflg );
    semctl ( semid, 0, SETVAL, 71 );                 //   set value 71
    // semaphore is an array. So, here 0 means, first item of this array
    printf("Set value\n");
return 0;
}


second.cpp
-----------------------------------------------------------------
#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()
{
    key_t key= 0x20 ;        
    int nsems = 1 ;             
    int semflg= 0666 | IPC_CREAT ;  
    int semid;                            

    semid = semget( key , nsems, semflg );  
    int 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 can now access semaphore variable.

মন্তব্যসমূহ