Wednesday, October 30, 2013

To implement SEMAPHORE in C

 /*
To implement SEMAPHORE in C

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

int main()
{
        int semid,pid,val,i,withdraw;
        struct sembuf sop;
        FILE *fp;
        int balance;
        semid=semget(0x20,1,IPC_CREAT|0666);
        semctl(semid,0,SETVAL,1);
        sop.sem_num=0;
        sop.sem_op=-1;
        sop.sem_flg=SEM_UNDO;
        pid=fork();
        if(pid==0)
        {
                printf("Child Before Sem Operation\n");
                semop(semid,&sop,1);
                printf("Child is in Critical Section\n");
                fp = fopen("data.txt","r+");
                fscanf(fp,"%d",&balance);
                printf("Enter the Amount to be Withdrawn: ");
                scanf(" %d",&withdraw);
                rewind(fp);
                balance = balance - withdraw;
                fprintf(fp,"%d",balance);
                fclose(fp);
                sleep(2);
                printf("\nBalance = %d\n",balance);
                printf("Child Outside Critical Section\n");
        }
        else
        {
                printf("Parent Before Sem Operation\n");
                semop(semid,&sop,1);
                printf("Parent is in Critical Section\n");
                sleep(2);
                fp = fopen("data.txt","r+");
                fscanf(fp,"%d",&balance);
                printf("\nBalance = %d\n",balance);
                printf("Enter the Amount to be Withdrawn: ");
                scanf(" %d",&withdraw);
                rewind(fp);
                balance = balance - withdraw;
                fprintf(fp,"%d",balance);
                fclose(fp);
                sleep(2);
                printf("\nBalance = %d\n",balance);
                printf("Parent Outside Critical Section\n");
        }
        return 0;
}

/* Output:
Child Before Sem Operation
Child is in Critical Section
Parent Before Sem Operation
Enter the Amount to be Withdrawn: 10

Balance = 850
Child Outside Critical Section
Parent is in Critical Section

Balance = 850
Enter the Amount to be Withdrawn: 50

Balance = 800
Parent Outside Critical Section
*/

No comments:

Post a Comment