Featured Post

Thursday, July 21, 2016

File Locking using semaphores


/* Create a file named akr in your user directory before executing this program and execute below semlock.c program*/



/*semlock.c*/

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/ipc.h>
int main()
{
  int sem1;

char a='5';
   sem1=semget(1212,1,IPC_CREAT|0666);/* creating semaphore */
  if(sem1<0)
  printf("not created semaphore");
   semctl(sem1,0,SETVAL,6);/ * setting value to semaphore */
   struct sembuf sem_op;
   FILE *fd;
    fd=fopen("/home/netsem2014/akr","a");
 
    sem_op.sem_num=0;
    sem_op.sem_op=-1;
     sem_op.sem_flg=0;
   semop(sem1,&sem_op,1);/* lock applied */    

putc('\n',fd);/trying to place data into file akr */
putc(a,fd);/trying to place data into file akr */
 fclose(fd);

sem_op.sem_num=0;
sem_op.sem_op=1;
sem_op.sem_flg=0;
semop(sem1,&sem_op,1);/*lock released */
}

/* the program trying to write something to a file akr but it cannot write anything to the file because the file is locked with semaphore at the time of writing. so there is no change in the content of the file */


/home/ashok/~ cat akr
hi hello how are you?   /*original file */


/home/ashok/~ cc semlock.c
/home/ashok/~ ./a.out


/home/ashok/~ cat akr
hi hello how are you?   /* after modification also no change      
                         because file locked by the semaphore */


IPC using semaphore, file locking, semget, semop, semctl functions, producer consumer problem, setting semaphore value



No comments:

Post a Comment