OS Lab Record_19

download OS Lab Record_19

of 58

Transcript of OS Lab Record_19

  • 7/27/2019 OS Lab Record_19

    1/58

    Ex No: 1 CPU Scheduling Algorithms

    / /08

    Problem Statement:

    To write program to implement the following CPU scheduling algorithms

    First come first served.

    Shortest job first

    Round robin scheduling

    Program Description:

    Get the process details, process name and burst time.

    Get the choice of scheduling algorithm

    FCFS:

    o Calculate waiting time and turn around time for process in the order of

    their arrival

    SJF:

    o Sort the processes based in their burst time and then calculate waiting time

    and turn around time for process.

    Round Robin:

    o Get the time quantum

    o Allow the process to run only for the time quantum

    o If it finishes, calculate total turn around time and waiting time

    o Else, put it in the back of queue and make it to wait for its chance

    1

  • 7/27/2019 OS Lab Record_19

    2/58

    Program Code:

    #include #include

    #include int numProc,tq;struct proc{

    char name[4];int bt;int wt;int tat;int priority;

    }job[10],fcfs[10],sjob[10],rr[10];

    void getProcDetails(){

    int i;printf("Enter number of processes\n");scanf("%d",&numProc);for(i=0;i

  • 7/27/2019 OS Lab Record_19

    3/58

    void swap(int i, int j){

    struct proc temp;temp = sjob[i];

    sjob[i] = sjob[j];sjob[j] = temp;

    }

    void fcfs_proc(struct proc p[]){int i, tmp=0;for(i=0;i

  • 7/27/2019 OS Lab Record_19

    4/58

    {flag++;rr[i].tat = c;rr[i].wt = rr[i].tat - rr[i].bt;

    }

    }else{

    c+=temp[i].bt;flag++;rr[i].tat = c;rr[i].wt = rr[i].tat - rr[i].bt;

    }}i++;if(i == numProc) i=0;

    if (flag == numProc) break;} /* while loop */displayProcDetails(rr);

    }

    void main(){int choice;clrscr();getProcDetails();while(1){printf("Enter Your Choice\n");printf("1. FCFS 2. SJF 3. RoundRobin 4. Exit\n");scanf("%d",&choice);switch(choice){case 1:

    fcfs_proc(fcfs);break;

    case 2:

    sjf_proc();break;case 3:

    rr_proc();break;

    case 4:exit(0);

    } /* switch */} /* while loop */

    } /* main function */

    4

  • 7/27/2019 OS Lab Record_19

    5/58

    Sample Output:

    Enter Process DetailsEnter Number of Processes:

    4Process name: p1Process Burst time: 5Process name: p2Process Burst time: 6Process name: p3Process Burst time: 12Process name: p4Process Burst time: 7Process name: p5Process Burst time: 9

    Enter Your Choice1. FCFS 2. SJF 3. RoundRobin 4. Exit1

    Name BTime WTime TATimep1 5 0 5p2 6 5 11p3 12 11 23p4 7 23 30

    p5 9 30 39

    Average Waiting Time 13.800000Average Turn Around Time 21.600000

    Enter Your Choice1. FCFS 2. SJF 3. RoundRobin 4. Exit2

    Name BTime WTime TATimep1 5 0 5

    p2 6 5 11p4 7 11 18p5 9 18 27p3 12 27 39

    Average Waiting Time 12.200000Average Turn Around Time 20.000000

    Enter Your Choice1. FCFS 2. SJF 3. RoundRobin 4. Exit3

    Enter time quantum1

    5

  • 7/27/2019 OS Lab Record_19

    6/58

    Name BTime WTime TATimep1 5 16 21p2 6 20 26p3 12 27 39

    p4 7 24 31p5 9 27 36

    Average Waiting Time 22.799999Average Turn Around Time 30.600000

    Enter Your Choice1. FCFS 2. SJF 3. RoundRobin 4. Exit4

    Result:

    Thus CPU Scheduling Algortighms FCS, SJF and RR were implemented, testedand verified.

    6

  • 7/27/2019 OS Lab Record_19

    7/58

    Ex No: 2 Dekkers Algorithm

    / /08

    Program Statement:

    To write a program to implement Dekkers algorithm to solve critical sectionproblem.

    Program Description:

    It is the first software solution to critical section problem

    Have two processes: P0, P1.

    Create Shared memory for both the processes

    Let P0 reads the number of integers and stores the values in the shared

    memory

    P0 sets the flag to TRUE and goes to critical section code (step 5)

    P0 adds the first half of the numbers and stores the result in shared

    memory.

    P0 sets the flag to FALSE says that it has completed its CS code

    P1 retrieves the number of elements by accessing the first locatiob of

    shared memory. It sits in in a loop until the flag becomes FALSE.

    Now, P1 enters into CS by setting the flag to TRUE.

    P1 adds the second half of the numbers to the result of process P0 and

    stores the result in shared memory.

    P1 sets the flag to FALSE and come out of CS.

    Finally P1 prints the total sum and P0 deletes the shared memory

    7

  • 7/27/2019 OS Lab Record_19

    8/58

    Program Code:

    /* dekker.c */

    #include#include#include#include#define true 1#define false 0

    main(){

    int flag1 = true, flag2 = false;int *a, i, j, n1, n2, sum1=0, sum2=0;int shmid, pid;

    shmid=shmget((key_t)999,sizeof(int)*20,IPC_CREAT|IPC_EXCL|0777);

    a=(int *)shmat(shmid,NULL,0777);if(a==(int *)-1){

    printf("shmat() error\n");

    exit(1);}

    printf("enter the no of elements\n");scanf("%d",&n1);

    printf("enter the nos\n");for(i=1;i

  • 7/27/2019 OS Lab Record_19

    9/58

    a[n2+1] = flag1; /* CS code begins */for(j=n2/2+1;j

  • 7/27/2019 OS Lab Record_19

    10/58

    Ex.no: 3 Semaphores

    / /08

    Problem statement:

    To implement Producer-Consumer problem using semaphores in UNIX system.

    Program Description:

    Create semaphore using semget() system call

    Set its value using semctl() system call

    If the process is to request for any resource, set sem_op field to -1 and call

    semop() sys call which does necessary update, such that any other process cannotmake requests for the same resource.

    If the process is to release for the availed resource, set sem_op field to 1 and call

    semop() sys call which does necessary update, such that new or waited processescan avail that resource.

    If the resource is held by any other process, the requested process waits in a loopand checks the semaphore value, whether it is released from the process whichholds it.

    delete() function removes the created semaphore at the exit of the program.

    10

  • 7/27/2019 OS Lab Record_19

    11/58

    Program Code:

    #include #include #include #include #include #include #include #include #include #define SHMDATASIZE 1000#define BUFFERSIZE (SHMDATASIZE - sizeof(int))

    #define SN_EMPTY 0#define SN_FULL 1#define SN_LOCK 2

    int DeleteSemId = 0, DeleteShmId=0;

    void consumer(int);void producer(int);int masterinit(void);

    char *standardinit(int,int *);void delete(void);void sigdelete(int);void locksem(int,int);void unlocksem(int,int);void producerwrite(int,int, char*);

    int main(int argc,char *argv[]){

    char selection[3];int shmid;

    /* No arguments: Server */if(argc < 2)shmid = masterinit();

    elseshmid = atoi(argv[1]);

    printf("Shall I be a [C]onsumer or [P]roducer process\n");fgets(selection,sizeof(selection),stdin);switch(selection[0]){

    case 'p':

    case 'P': producer(shmid); break;case 'c':

    11

  • 7/27/2019 OS Lab Record_19

    12/58

    case 'C': consumer(shmid); break;default: printf("Invalid choice, exiting\n");

    exit(0);} /* end switch */return 0;

    }

    void producer(int shmid){

    int semid;char *buffer;

    buffer = standardinit(shmid, &semid);printf("Produce operational: shm id is %d, sem id is %d\n", shmid,semid);

    while(1){char input[3];printf("\t\t\tMenu\n1. Send a message\n 2. Exit\n");fgets(input, sizeof(input),stdin);

    switch(input[0]){{

    case '1': producerwrite(shmid,semid,buffer); break;case '2': exit(0);

    }} /* end while */

    }

    void consumer(int shmid){int semid;char *buffer;

    buffer = standardinit(shmid, &semid);

    printf("Consumer operation: shmid %d, semid %d\n",shmid,semid);

    while(1){

    printf("Waiting until full ... \n");fflush(stdout);locksem(semid,SN_FULL);printf("done\n");

    printf("Waiting for lock ... \n");fflush(stdout);

    locksem(semid,SN_LOCK);printf("done\n");

    12

  • 7/27/2019 OS Lab Record_19

    13/58

    printf("Message received %s\n",buffer);unlocksem(semid,SN_LOCK);unlocksem(semid,SN_EMPTY);

    } /* end while */

    }

    char *standardinit(int shmid, int *semid){

    void *shmdata;char *buffer;

    shmdata = shmat(shmid,0,0);if(shmdata == (int *)-1 ){printf("shmat() error\n");

    exit(0);}*semid = *(int *)shmdata;buffer = shmdata + sizeof(int);return buffer;

    }

    int masterinit(void){

    int semid, shmid;void *shmdata;

    semid = semget(IPC_PRIVATE, 3, SHM_R|SHM_W);if(semid == -1 ){printf("semget() error\n");exit(0);

    }DeleteSemId = semid;

    atexit(&delete);

    signal(SIGINT, &sigdelete);

    /* Initially empty should be available and full should not be.The lock will also be available initially */

    if(semctl(semid,SN_EMPTY, SETVAL, 1) == -1){printf("semctl() SN_EMPTY error\n");exit(0);

    }if(semctl(semid,SN_LOCK, SETVAL, 1) == -1)

    {printf("semctl() SN_LOCK error\n");

    13

  • 7/27/2019 OS Lab Record_19

    14/58

    exit(0);}if(semctl(semid,SN_FULL, SETVAL, 0) == -1){printf("semctl() SN_FULL error\n");

    exit(0);}

    /* Allocate shared memory segment */shmid = shmget(IPC_PRIVATE, SHMDATASIZE, IPC_CREAT|SHM_R|SHM_W);if(shmid == -1){printf("shmget() error\n");exit(0);

    }DeleteShmId = shmid;

    /* Map it to memory */shmdata = shmat(shmid,0,0);if(shmdata == (int *)-1){printf("semctl() error\n");exit(0);

    }

    /* Write the semaphore id to the beginning */*(int *)shmdata = semid;

    printf("*** The system is running with SHM id %d",shmid);return shmid;

    }

    void delete(void){

    printf("Master exiting; deleting semaphore %d\n", DeleteSemId);if(semctl(DeleteSemId,0,IPC_RMID,0) == -1)printf("Error in releasing semaphore\n Use the command `ipcrm sem ` at

    the command prompt\n");

    /* Mark it to delete automatically when the last holding process exits */if(shmctl(DeleteShmId, IPC_RMID, NULL) == -1){printf("semctl() IPC_RMID error\n");exit(0);

    }}

    void sigdelete(int signum){

    exit(0);}

    14

  • 7/27/2019 OS Lab Record_19

    15/58

    void locksem(int semid, int semnum){

    struct sembuf sb;

    sb.sem_num = semnum;sb.sem_op = -1;sb.sem_flg = SEM_UNDO;

    if(semop(semid, &sb, 1) == -1){printf("semop() locksem error\n");exit(0);

    }}

    void unlocksem(int semid, int semnum){

    struct sembuf sb;

    sb.sem_num = semnum;sb.sem_op = 1;sb.sem_flg = SEM_UNDO;

    if(semop(semid, &sb, 1) == -1){printf("semop() unlocksem error\n");exit(0);

    }}

    void producerwrite(int shmid, int semid, char *buffer){printf("Waiting until empty ...\n");fflush(stdout);locksem(semid,SN_EMPTY);

    printf("done. waiting for lock ...\n");fflush(stdout);locksem(semid,SN_LOCK);

    printf("Enter message\n");fgets(buffer, BUFFERSIZE, stdin);

    unlocksem(semid,SN_LOCK);unlocksem(semid,SN_FULL);

    }

    15

  • 7/27/2019 OS Lab Record_19

    16/58

    Sample Output:

    Window 1 (Producer)

    $ ./prod_con*** The system is runningwith SHM id $ cc o

    prod_con prod_con.c884738 Shall I be a[C]onsumer or [P]roducer

    process

    PProduce operational:shm id is 884738,sem id is 327682

    Menu1. Send a message2. Exit

    1Waiting until empty ...done. waiting for lock ...Enter message

    Welcome, Good Morning!!

    Menu1. Send a message2. Exit

    1Waiting until empty ...done. waiting for lock ...Enter messageGood Luck, All the Best!!

    Menu1. Send a message2. Exit

    1Waiting until empty ...done. waiting for lock ...Enter messageGood Luck, All the Best!!

    Menu1. Send a message

    Window 2 (Consumer 1)

    $ ./prod_con 884738Shall I be a [C]onsumer or[P]roducer processC Consumer operation:shmid 884738,semid 327682Waiting until full ...

    doneWaiting for lock ...doneMessage receivedWelcome, Good Morning!!

    Waiting until full ...

    doneWaiting for lock ...doneMessage receivedBye, Good Night!!Waiting until full ...

    Window 3 (Consumer 3)

    $ ./prod_con 884738Shall I be a [C]onsumer or[P]roducer processC Consumer operation:shmid 884738,semid 327682Waiting until full ...

    doneWaiting for lock ...doneMessage receivedWelcome, Good Morning!!

    Waiting until full ...

    16

  • 7/27/2019 OS Lab Record_19

    17/58

    2. Exit2$

    $ $

    Result:

    Thus inter process communication using semaphores in UNIX was implemented,tested and verified.

    17

  • 7/27/2019 OS Lab Record_19

    18/58

    Ex No: 4 Memory Management Techniques

    / /08

    Problem Statement:

    To write program to implement frist fir, best fit and worst fit strategies.

    Program Description:

    Get the partition details - number of partitions, partition size.

    Get the process details - number of processes, process size.

    For First Fit algorithm, for each process

    o Start searching from beginning and continue searching as long as we find a

    free hole that is large enough.o Allocate that partition to hold the process

    For best fit algorithm, for each process

    o Search entire free partition list and find a partition that causes the least

    amount of potential fragmentationo Allocate that partition to hold the process

    For worst fit algorithm, for each process

    o Search the entire free partition list and find a partition that is larger.

    o Allocate that partition to hold the process

    For each of the algorithms, calculate the amount of left over holes in the partition.

    Compare them and print which uses efficient use of memory (one which has small

    leftover hole)

    18

  • 7/27/2019 OS Lab Record_19

    19/58

    Program Code:

    #include #include #include

    struct memPart{

    int partNo;int size;int flag;int freeSpace;

    }partition[10];

    struct memProc{

    int procNo;int size;int flag;int partNo;

    }process[10];

    void bestfit(int numProc, int numPart)

    {int i,j, lowkey, lowindex;for(i=0;i

  • 7/27/2019 OS Lab Record_19

    20/58

    {partition[lowindex].flag = process[i].flag = 1;process[i].partNo = lowindex;partition[lowindex].freeSpace = partition[lowindex].size - process[i].size;break;

    }elsecontinue;

    } /* if partition[j].flag */} /* j for loop */} /* if process[i].flag */if (process[i].flag == 0)process[i].partNo = 99;

    } /* i for loop */}

    void firstfit(int numProc, int numPart){

    int i,j;

    for(i=0;i

  • 7/27/2019 OS Lab Record_19

    21/58

    {if(partition[j].flag == 0){maxkey = partition[j].size;maxindex = j;

    for(int k=j+1;k maxkey){

    maxkey = partition[k].size;maxindex=k;

    }}

    } /* k for loop */

    if( process[i].size

  • 7/27/2019 OS Lab Record_19

    22/58

    printf("%4d%13d%13d\n",partition[i].partNo,partition[i].size,partition[i].freeSpace);elseprintf("%4d%13d%13d

    %18s\n",partition[i].partNo,partition[i].size,partition[i].freeSpace,"Unused");}

    getch();}

    void main(){int i,choice,numPart,numProc;clrscr();printf("Enter partition details\n");printf("Enter number of partitions\n");scanf("%d",&numPart);printf("Enter partition size\n");

    for(i=0;i

  • 7/27/2019 OS Lab Record_19

    23/58

    exit(0);} /* switch */

    } /* while */} /* main function */

    Sample Output:

    Enter partition detailsEnter number of partitions

    4Enter partition size150200250300

    Enter process detailsEnter number of processes4

    Enter process size50300275180

    1. FirstFit 2. Best Fit 3. Worst Fit 4. Exit1-------- Allocation Details --------ProcNo ProcSize Allocated To

    Partition

    0 50 01 300 32 275 Not Allocated3 180 1

    Partition Partition PartitionNumber Size Free Space

    0 150 1001 200 20

    2 250 250 Unused3 300 0

    23

  • 7/27/2019 OS Lab Record_19

    24/58

    1. FirstFit 2. Best Fit 3. Worst Fit 4. Exit2-------- Allocation Details --------

    ProcNo ProcSize Allocated ToPartition

    0 50 01 300 32 275 Not Allocated3 180 1

    Partition Partition PartitionNumber Size Free Space

    0 150 100

    1 200 202 250 250 Unused3 300 0

    1. FirstFit 2. Best Fit 3. Worst Fit 4. Exit3-------- Allocation Details --------ProcNo ProcSize Allocated To

    Partition0 50 31 300 Not Allocated2 275 Not Allocated3 180 2

    Partition Partition PartitionNumber Size Free Space

    0 150 150 Unused1 200 200 Unused2 250 70

    3 300 250

    Result:

    Thus the various storage allocation techniques like First Fit, Best Fit and Worst Fitwere implemented, tested and verified.

    24

  • 7/27/2019 OS Lab Record_19

    25/58

    Ex No: 5 FIFO Page Replacement Algorithm

    / /08

    Problem Statement:

    To write a program to implement the First In First Out Page Replacement Algorithm

    Problem Description:

    Get the number of pages in page reference string

    Get the page reference string

    Get the number of frames

    FIFO algorithm:

    o For each page in reference string,

    o If a page is already in memory, then it is done.

    o If it is not in memory, increment the page fault.

    o If there is any free frame, load the required page into the free frame found.

    o Else, replace the page, which is brought into memory first.

    Print the total page faults that have been occurred.

    25

  • 7/27/2019 OS Lab Record_19

    26/58

    Program Code:

    #include#include

    void main(){int ref[25];int mem[10];int i,j,k,flag,n,m,p,pf;clrscr();printf("Enter the number of pages in the reference string \n");scanf("%d",&n);printf("enter the reference string \n");for (i=0;i

  • 7/27/2019 OS Lab Record_19

    27/58

    j++;} /* if flag != 1 */tem: printf("%d-- %d %d %d\n",p,mem[0],mem[1],mem[2]);} /* for i loop */

    printf("Number of page faults:%d\n",pf);getch();}

    Sample Output:

    Enter the number of pages in the reference string20enter the reference stringEnter the 1 page reference:7Enter the 2 page reference:0Enter the 3 page reference:1Enter the 4 page reference:2Enter the 5 page reference:0Enter the 6 page reference:3Enter the 7 page reference:0Enter the 8 page reference:4Enter the 9 page reference:2Enter the 10 page reference:3

    Enter the 11 page reference:0Enter the 12 page reference:3Enter the 13 page reference:2Enter the 14 page reference:1Enter the 15 page reference:2Enter the 16 page reference:0Enter the 17 page reference:1Enter the 18 page reference:7Enter the 19 page reference:0Enter the 20 page reference:1

    Enter the number of frames3

    FIFO Page Replacement Algorithm--------------------------------------------

    7-- 7 -1 -10-- 7 0 -11-- 7 0 12-- 2 0 10-- 2 0 13-- 2 3 10-- 2 3 0

    4-- 4 3 02-- 4 2 0

    27

  • 7/27/2019 OS Lab Record_19

    28/58

    3-- 4 2 30-- 0 2 33-- 0 2 32-- 0 2 31-- 0 1 3

    2-- 0 1 20-- 0 1 21-- 0 1 27-- 7 1 20-- 7 0 21-- 7 0 1

    Number of page faults:15

    Result:Thus the FIFO page replacement was implemented, tested and verified.

    28

  • 7/27/2019 OS Lab Record_19

    29/58

    Ex No: 6 LRU Page Replacement Algorithm

    / /08

    Problem Statement:

    To write a program to implement the Least Recently Used Page ReplacementAlgorithm

    Problem Description:

    Get the number of pages in page reference string

    Get the page reference string

    Get the number of frames

    LRU algorithm:

    o For each page in the reference string, if a page is already in memory, then

    it is doneo If it is not in memory, increment the page fault.

    o If there is any free frame, load the required page into the free frame found.o Else, replace the page that has not been used for the longest period of time

    by checking the previous reference strings.

    Print the page faults for each of the schemes.

    29

  • 7/27/2019 OS Lab Record_19

    30/58

    Program Code:

    #include#include

    void main(){int ref[25];int mem[10],memf[]={0,0,0};int i,j,k,flag,n,m,p,pf,ch;clrscr();printf("Enter the number of pages in the reference string \n");scanf("%d",&n);printf("enter the reference string \n");for (i=0;i

  • 7/27/2019 OS Lab Record_19

    31/58

    {p=ref[i];flag=0;

    for(k=0;k

  • 7/27/2019 OS Lab Record_19

    32/58

    Sample Output:

    Enter the number of pages in the reference string20enter the reference string

    Enter the 1 page reference:7Enter the 2 page reference:0Enter the 3 page reference:1Enter the 4 page reference:2Enter the 5 page reference:0Enter the 6 page reference:3Enter the 7 page reference:0Enter the 8 page reference:4Enter the 9 page reference:2Enter the 10 page reference:3Enter the 11 page reference:0

    Enter the 12 page reference:3Enter the 13 page reference:2Enter the 14 page reference:1Enter the 15 page reference:2Enter the 16 page reference:0Enter the 17 page reference:1Enter the 18 page reference:7Enter the 19 page reference:0Enter the 20 page reference:1

    Enter the number of frames3

    LRU Algorithm-----------

    7-- 7 -1 -10-- 7 0 -11-- 7 0 12-- 2 0 10-- 2 0 13-- 2 0 3

    0-- 2 0 34-- 4 0 32-- 4 0 23-- 4 3 20-- 0 3 23-- 0 3 22-- 0 3 21-- 1 3 22-- 1 3 20-- 1 0 21-- 1 0 2

    7-- 1 0 70-- 1 0 7

    32

  • 7/27/2019 OS Lab Record_19

    33/58

    1-- 1 0 7Number of page faults :12

    Result:Thus the LRU page replacement algorithms was implemented, tested and verified.

    Ex no: 7 Shared Memory

    / /08

    Problem Statement:

    To write a program to implement shared memory between two unrelatedprocesses.

    Program Description:

    Process P1

    Creates shared memory

    Attach it to shared memory.

    Get the array of numbers and store them in the shared memory

    Sum first n/2 numbers and prints the result

    Detach from shared memory

    Delete shared memory

    Process P2

    Attach to shared memory.

    33

  • 7/27/2019 OS Lab Record_19

    34/58

    Gets the number of elements from the first location of shared memory

    Sum second half numbers and prints the result

    Also print the sum of n numbers

    Detach from shared memory

    Program Code:

    /* sm1.c */

    #include#include#include#include

    void main(){

    int *a,i,sum=0,shmid,n;shmid=shmget((key_t)123,sizeof(int)*20,IPC_CREAT|IPC_EXCL|0777);

    a=(int *)shmat(shmid,NULL,0777);if(a==(int *)-1){

    printf("failure");exit(1);

    }printf("enter the no of elements\n");scanf("%d",&n);

    printf("enter the nos\n");for(i=1;i

  • 7/27/2019 OS Lab Record_19

    35/58

    sum = sum +a[i];a[n+2]=sum;printf(" Process 1, sum of first half elements = %d\n",sum);shmdt(a);shmctl(shmid,IPC_RMID,0);

    }

    /* sm2.c */

    #include#include#include#includevoid main(){int *a,i,sum=0, total = 0, shmid,n;

    shmid=shmget((key_t)123,sizeof(int)*20,0777);

    a=(int *)shmat(shmid,NULL,0777);n=a[0];for(i=n/2+1;i

  • 7/27/2019 OS Lab Record_19

    36/58

    $./sm2 (in another window)Prcoess 2 Sum of elements = 40Sum of 10 elements = 55

    Result:

    Thus the inter process communication using shared memory in UNIXwas implemented, tested and verified

    EX No: 8 FILE LOCKING

    / /08

    Problem Statement:

    To write a program to implement File Locking algorithm in Unix System.

    Program Description:

    Initialize struct flock with the type of lock required

    Open the file with the matching mode

    Call fcntl() with the initialized lock structure

    Update the file

    Clear the lock by setting F_UNLCK field and call fcntl().

    File locking is a mechanism that enforces access to a computer file by only one user orprocess at any specific time.

    Types of locking mechanisms: Mandatory Locking and Advisory Locking.

    Mandatory lock systems actually prevent read() and write() to file, but with an

    advisory lock systems, processes can still read and write from a file while it's locked.

    36

  • 7/27/2019 OS Lab Record_19

    37/58

    There are two types of advisory locks: read locks and write locks (also referred to asshared locks and exclusive locks, respectively.) The way read locks work is that theydon't interfere with other read locks. For instance, multiple processes can have a filelocked for reading at the same time. However, when a process has write lock on a file, noother process can activate either a read or write lock until it is relinquished. One easy way

    to think of this is that there can be multiple readers simultaneously, but there can only beone writer at a time.

    There are many ways to lock files in Unix systems - l ockf(), flock(), fcntl() andcreate() with O_EXCL flag.

    Setting a lock

    The fcntl() function does everything, just we need to fill up the struct flock(declared infcntl.h) that describes the type of lock needed, open() the file with the matching mode,and call fcntl() with the proper arguments.

    Here are some field definitions:

    l_type

    It signifies the type of lock that need to be set. It's either F_RDLCK, F_WRLCK, orF_UNLCK i.e. it sets a read lock, a write lock or clear the lock respectively.

    l_whence

    It determines where the l_start field starts from (it's like an offset for the offset). It can beeither SEEK_SET, SEEK_CUR, or SEEK_END, for beginning of file, current file

    position or end of file respectively.

    l_start

    This is the starting offset in bytes of the lock, relative to l_whence.

    l_len

    This is the length of the lock region in bytes (which starts from l_start which is relative tol_whence.

    Lock types and corresponding open() modes.

    l_type modeF_RDLCK O_RDONLY or O_RDWRF_WRLCK O_WRONLY or O_RDWR

    The second argument to fcntl() tells it what to do with the data passed to it in the structflock. The following list summarizes what each fcntl() cmd does:

    F_SETLKW

    This argument tells fcntl() to attempt to obtain the lock requested in the struct flockstructure. If the lock cannot be obtained (since someone else has it locked already), fcntl()will wait (block) until the lock has cleared, then will set it itself.

    F_SETLK

    37

  • 7/27/2019 OS Lab Record_19

    38/58

    This function is almost identical to F_SETLKW. The only difference is that this one willnot wait if it cannot obtain a lock. It will return immediately with -1. This function can beused to clear a lock by setting the l_type field in the struct flock to F_UNLCK.

    F_GETLK

    This is used to get the lcok status of any file, but does not set lock. It copies the lock'sinformation into the struct and returns back. If it can't find any conflicting lock, fcntl()returns the struct with l_type field set to F_UNLCK.

    Clearing the lock

    Just change the l_type to F_UNLCK and call fcntl();

    File locks are based on inode instead of file name, since UNIX allows multiple names torefer to the same file. All fcntl locks associated with a file for a given process areremoved when any file descriptor for that file is closed by that process, even if a lock was

    never requested for that file descriptor. Also, fcntl locks are not inherited by a childprocess.

    Program Code:

    /* file1_lock.c using lockf() sys call */

    #include #include #include #include

    #define SEQFILE "test.txt"#define MAXBUFF 100

    void my_lock(int fd){

    if(lockf(fd,F_LOCK,0L) == -1)printf("Error in file locking\n");

    }

    void my_unlock(int fd){

    if(lockf(fd,F_ULOCK,0L) == -1)printf("Error in file locking\n");

    }

    int main(){

    38

  • 7/27/2019 OS Lab Record_19

    39/58

    int fd, i, n, pid, seqno;char buff[MAXBUFF+1];

    pid = getpid();

    if( (fd=open(SEQFILE, O_RDWR)) == -1){

    printf("Error in opening the file\n");exit(0);

    }

    for(i=0;i

  • 7/27/2019 OS Lab Record_19

    40/58

    printf("Error in file locking\n");}

    void my_unlock(int fd){

    if(flock(fd,LOCK_UN) == -1)printf("Error in file locking\n");

    }

    /* file3_lock.c using fcntl() sys call */void my_lock(int fd){

    struct flock f;

    f.l_type = F_WRLCK;

    f.l_whence = SEEK_SET;f.l_start = 0;f.l_len = 0;

    if(fcntl(fd,F_SETLKW,&f) == -1)printf("Error in file locking\n");

    }

    void my_unlock(int fd){

    struct flock f;

    f.l_type = F_WRLCK;f.l_whence = SEEK_SET;f.l_start = 0;f.l_len = 0;

    if(fcntl(fd,F_UNLCK,&f) == -1)printf("Error in file locking\n");

    }

    Sample Output:

    $ ./file3_lock (in one window)pid= 5455, 0pid= 5455, 1pid= 5455, 2pid= 5455, 3pid= 5455, 4pid= 5455, 5

    pid= 5455, 6pid= 5455, 7

    40

  • 7/27/2019 OS Lab Record_19

    41/58

    pid= 5455, 8pid= 5455, 9pid= 5455, 10pid= 5455, 11pid= 5455, 12

    pid= 5455, 13pid= 5455, 14pid= 5455, 15pid= 5455, 16pid= 5455, 17pid= 5455, 18pid= 5455, 19

    $ ./file3_lock & (in second window)[1] 5456

    pid= 5456, 20pid= 5456, 21pid= 5456, 22pid= 5456, 23pid= 5456, 24pid= 5456, 25pid= 5456, 26pid= 5456, 27pid= 5456, 28pid= 5456, 29pid= 5456, 30pid= 5456, 31pid= 5456, 32pid= 5456, 33pid= 5456, 34pid= 5456, 35pid= 5456, 36pid= 5456, 37pid= 5456, 38pid= 5456, 39

    41

  • 7/27/2019 OS Lab Record_19

    42/58

    Result:

    Thus the File Locking was implemented, tested and verified in UNIX system.

    Ex No: 9 Bankers Algorithm

    / /08

    Problem statement:

    To write program to implement the Bankers Algorithm to avoid deadlock

    Program Description:

    Get the number of process, n.

    Get the number of resource types, m.

    Get the maximum resource availability, totalR

    Get the maximum needs for each process, max and current allocated information,

    current

    Calculate the available vector by subtracting totalR from the column values of

    current vector and need vector = Max-Current.

    Safety Algorithm: Checks whether each process is in safe state or not.

    For each process, for each resource, check if the need vector is greater than availvector. If so, then the system is unsafe state; else the system is in safe state. If the

    42

  • 7/27/2019 OS Lab Record_19

    43/58

    system is safe, pretend the request can be granted, increase the avail vector,subtract the allocated information and mark the process finished.

    Get equest from some process some process i.

    Check the validity of request using resource request algorithm. The request vectorshould not be greater than the Max[i]-current[i]. If the request vector is less thanthe avail vector, the process can be granted new request. Then check the safety ofthe system.

    Program Code:

    #include

    #include #include

    #define safe 1#define unsafe 0

    int max[10][10], current[10][10], need[10][10], allocated[10], avail[10], totalR[10];int flag[10], finish[10];

    void check_safe(int i, int n, int r){

    int j;

    //printf("Evaluating availability of resources\n");

    if(finish[i] == 0){for(j=0;j

  • 7/27/2019 OS Lab Record_19

    44/58

    flag[i] = unsafe;break;

    }} /* for j loop */if(flag[i] == safe)

    {printf("Resources can be granted to process %d\n",i);printf("Now the availability is\n");for(j=0;j= totalR[j])

    avail[j] = totalR[j];printf("%d\t",avail[j]);

    }

    printf("\n");finish[i] = 1;

    } /* if flag[i] == safe */else if(flag[i] == unsafe)

    printf("Resources cannot be granted to %d\n It may lead to deadlock\n",i);} /* if finish[i] check *///getch();} /* check_safe ends */

    void request_res(int n, int r){

    int p_no, req[10];int i, j, flag=0;

    printf("Enter the process for which the resource is needed\n");scanf("%d",&p_no);printf("Enter the extra resources needed\n");for(i=0;i

  • 7/27/2019 OS Lab Record_19

    45/58

    printf("Invalid request\n");return;

    } /* if flag == 0 */

    /* granting the requested resources, checking safety */

    else{for(i=0;i

  • 7/27/2019 OS Lab Record_19

    46/58

    printf("Enter the max availability of resources\n");for(j=0;j

  • 7/27/2019 OS Lab Record_19

    47/58

    case 3:exit(0);

    }}while(choice

  • 7/27/2019 OS Lab Record_19

    48/58

    Now the availability is 5 5 7

    Total Resources available 7 7 10Currently allocated resources 2 2 3Currently available resources 5 5 7

    Menu1. Check Safe2. Request resource3. Exit

    Enter your choice2

    Enter the process for which the resource is needed0

    Enter the extra resources needed1 1 0Resources can be granted to process 0

    Now the availabiltiy is 7 7 10Total Resources available 7 7 10Currently allocated resources 0 0 0Currently available resources 7 7 10

    Menu1. Check Safe2. Request resource3. Exit

    Enter your choice2Enter the process for which the resource is needed0Enter the extra resources needed2 1 3

    Invalid Request

    Total Resources available 7 7 10Currently allocated resources 2 2 3Currently available resources 5 5 7

    Menu1. Check Safe2. Request resource3. Exit3

    48

  • 7/27/2019 OS Lab Record_19

    49/58

    Result:

    Thus the Banker's algorithm to avoid deadload was implemented, tested andverified.

    Ex No: 10 Disk Scheduling Algorithms

    / /08

    Problem Statement:

    To write a program to implement the following disk scheduling algorithms

    FCFS

    SSTF

    SCAN

    C-SCAN

    LOOK

    C-LOOK

    Problem Description:

    Get the number of cylinders, nc and the number of requests, nr

    Get the current head position, head.

    Get the requests, treq[]

    Total head movement = Number of cylinders that head moved to process requests.

    FCFS scheduling: Process the requests in order of their arrival and calculate total head movement

    49

  • 7/27/2019 OS Lab Record_19

    50/58

    SSTF scheduling:

    For each request, find the request, which is closest to the current head position and

    process that request.

    SCAN scheduling: Get the previous request

    Find the direction of head movement.

    Process the requests that are in the way of head movement

    If the head reaches end of cylinder, then it is made to reverse the direction and

    continue to process the requests.

    LOOK scheduling: Get the previous request

    Find the direction of head movement.

    Process the requests that are in the way of head movement

    If the head reaches last request in that direction of movement, then it is made to

    reverse the direction and continue process the requests.

    C-SCAN scheduling: Get the previous request

    Find the direction of head movement.

    The head moves in only one direction.

    Process the requests that are in the way of head movement,

    If the head reaches last request in the direction of head movement, then instead of

    reversing the direction of head, it is swept back to the location where next request ismade from beginning without processing requests on return paths and then continue.

    C-LOOK scheduling:

    Get the previous request

    Find the direction of head movement.

    The head moves from one end to other end

    Process the requests that are in the way of head movement

    50

  • 7/27/2019 OS Lab Record_19

    51/58

    If the head reaches end of cylinder, then instead of reversing the direction of head, it

    is swept back to the starting location without processing requests on return paths andthen continue.

    Program Code;

    #include #include #include

    int nc, nr, head, prev, treq[20];int thm=0;

    void sort_asc(int l[], int ln){

    int i,j, temp;

    for(i=0;i

  • 7/27/2019 OS Lab Record_19

    52/58

    if(g[i] < g[j]){

    temp = g[i]; g[i] = g[j]; g[j] = temp;}

    }

    void calc_thm(int g[], int l[], int gn, int ln, int head){

    int i;thm = 0;thm += abs(head-g[0]);for(i=0;i

  • 7/27/2019 OS Lab Record_19

    53/58

    }printf("%d\n",treq[i]);printf("Total Head Movement %d\n",thm);

    }

    void sstf(){

    int thead, req[20], i, min_index;thead = head;for(i=0;i 0){

    g[gn++] = nc-1;sort_asc(g,gn);sort_desc(l,ln);calc_thm(g,l,gn,ln,head);

    }else{

    l[ln++] = 0;sort_asc(g,gn);

    53

  • 7/27/2019 OS Lab Record_19

    54/58

    sort_desc(l,ln);calc_thm(l,g,ln,gn,head);

    }}

    void look(){

    int i, ln=0, gn=0, l[20], g[20];thm = 0;printf("%d -> ",head);for(i=0;i head)g[gn++] = treq[i];

    elsel[ln++] = treq[i];

    }sort_asc(g,gn);sort_desc(l,ln);if(head-prev > 0)calc_thm(g,l,gn,ln,head);

    elsecalc_thm(l,g,ln,gn,head);

    }

    void c_scan(){

    int i, ln=0, gn=0, l[20], g[20];thm = 0;printf("%d -> ",head);for(i=0;i head)g[gn++] = treq[i];

    elsel[ln++] = treq[i];

    }

    g[gn++] = nc-1;l[ln++] = 0;if(head-prev > 0){sort_asc(g,gn);sort_asc(l,ln);calc_thm(g,l,gn,ln,head);

    }else{sort_desc(g,gn);

    sort_desc(l,ln);calc_thm(l,g,ln,gn,head);

    54

  • 7/27/2019 OS Lab Record_19

    55/58

    }}

    void c_look(){

    int i, ln=0, gn=0, l[20], g[20];thm = 0;printf("%d -> ",head);for(i=0;i head)g[gn++] = treq[i];

    elsel[ln++] = treq[i];

    }

    if(head-prev > 0){sort_asc(g,gn);sort_asc(l,ln);calc_thm(g,l,gn,ln,head);

    }else{sort_desc(g,gn);sort_desc(l,ln);calc_thm(l,g,ln,gn,head);

    }}

    void main(){int choice;int i;

    clrscr();printf("Enter number of cylinders and requests\n");

    scanf("%d%d",&nc,&nr);printf("Enter the current head position\n");scanf("%d",&head);for(i=0;i

  • 7/27/2019 OS Lab Record_19

    56/58

    switch(choice){

    case 1:printf("=========FCFS Disk Scheduling=========\n");fcfs();

    break;case 2:

    printf("=========SSTF Disk Scheduling=========\n");sstf();

    break;case 3:

    printf("=========SCAN Disk Scheduling=========\n");printf("Enter previous request\n");scanf("%d",&prev);scan();

    break;

    case 4:printf("=========LOOK Disk Scheduling=========\n");printf("Enter previous request\n");scanf("%d",&prev);look();

    break;case 5:

    printf("=========C-SCAN Disk Scheduling=========\n");printf("Enter previous request\n");scanf("%d",&prev);c_scan();

    break;case 6:

    printf("=========C-LOOK Disk Scheduling=========\n");printf("Enter previous request\n");scanf("%d",&prev);c_look();

    break;case 7:

    exit(0);} /* end switch */

    } while(choice

  • 7/27/2019 OS Lab Record_19

    57/58

    Enter the request 2:17Enter the request 3:25Enter the request 4:50Enter the request 5:2Enter the request 6:40

    Enter the request 7:23

    FCFS scheduling21 ->3 5-> 17->2 S-> 50->2->40->2 3Total head movement:168

    SSTF scheduling21->23->25->17->2->35->40->50Total head movement:75

    SCAN scheduling

    Enter the previous request serviced1021->23->25->35->40->50->99->17->2Total head movement:175

    C-SCAN schedulingEnter the previous request serviced1021->23->25->35->40->50->99->0->2->17Total head movement.194

    LOOK schedulingEnter the previous request serviced1021->23->25->35^40->50->17->2Total head movemcnt:77

    C-LOOK schedulingEnter the previous request serviced1021->23->25->35->40->50->2->17

    Total head movement: 92

    57

  • 7/27/2019 OS Lab Record_19

    58/58

    Result:

    Thus the various disk scheduling algorithms like FCFS, SSTF, SCAN, C-SCAN,LOOK and C-LOOK were implemented, tested and verified.