Saturday, September 1, 2007

semaphore program in C

Semaphore program in C

/* basic semaphore example 1 */

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


main()
{
int sid;
int key,nsem;
key=(key_t)0x30;
nsem=1;
sid=semget(key,nsem,IPC_CREAT0777);
printf("\nSemaphore was created with the id = %d\n",sid);

}

/* basic semaphore example 2*/

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


main()
{
int sid;
int key,nsem;
key=(key_t)0x30;
nsem=1;
sid=semget(key,nsem,IPC_CREAT0666);
printf("\nSemaphore was created with the id = %d\n",sid);
sleep(15);
semctl(sid,0,IPC_RMID,0);
}


/* readers */

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


void sem_wait (int);
void sem_signal(int);


main(){
int rdcnt,wrt,mutex;
key_t rdkey=0x20;
key_t wrkey=0x30 ;

rdcnt = semget(rdkey,1,0666IPC_CREAT);
wrt = semget(wrkey,1,0666IPC_CREAT);
mutex = semget(0x40 ,1,0666IPC_CREAT);

semctl(mutex,0,SETVAL,1);
printf("\nStarting to Read.....");
sem_wait(mutex);
sem_signal(rdcnt);
sleep(10);
printf("\nReading Finished");
sem_wait(rdcnt);
sem_signal(mutex);

}


void sem_wait(int id){
struct sembuf buf = { 0,-1,0};
semop(id,&buf,1);
}

void sem_signal(int id){
struct sembuf buf = { 0,1,0};
semop(id,&buf,1);


}

No comments: