final copy oslab manua1. jjjjjjjjjjj 2

Upload: vaishalisingh

Post on 03-Jun-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    1/65

    SEC CSE/IV OS LAB MANUAL

    1

    SRINIVASAN ENGINEERING COLLEGE

    COMPUTER SCIENCE AND ENGINEERING

    ANNA UNIVERSITY OF TECHNOLOGY TRICHIRAPALLI

    REGULATION 2009

    II CSE (2011-2015)

    CS2257

    OPERATING SYSTEM LAB

    LAB MANUAL

    BY

    VEENA ALPHONSA JOSE, Assistant Professor.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    2/65

    SEC CSE/IV OS LAB MANUAL

    2

    Preface

    This laboratory manual is prepared by the Department of Computer Science and engineering

    for Operating system Laboratory (CS-2257). This lab manual can be used as instructional book for

    students, staff and instructors to assist in performing and understanding the experiments. In the first

    part of the manual, experiments as per syllabus are described and in the second part of the manual,

    experiments that are beyond the syllabus but expected for university laboratory examination are

    displayed. This manual will be available in electronic form from Colleges official website, for the

    betterment of students.

    Acknowledgement

    We would like to express our profound gratitude and deep regards to the support offered by

    the Chairman Shri. A.Srinivasan. We also take this opportunity to express a deep sense of

    gratitude to our Principal Dr.B.Karthikeyan,M.E,Ph.D, for his valuable information and

    guidance, which helped us in completing this task through various stages. We extend our hearty

    thanks to our head of the department Asst Prof.P.Jayanthi M.E, for her constant encouragement

    and constructive comments.

    Finally the valuable comments from fellow faculty and assistance provided by thedepartment are highly acknowledged.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    3/65

    SEC CSE/IV OS LAB MANUAL

    3

    TABLE OF CONTENTS

    CHAPTER NO TOPIC PAGE NO

    I

    Introduction to the languageMain Features

    Advantages

    Limitations

    Applications

    4

    II Syllabus 6

    III System Requirements 7

    IV

    Description about each experiment

    Aim

    Learning ObjectiveGeneral procedure to executeprograms

    8

    V Experiments

    1 Write programs using the following system calls of UNIXoperating system: fork, exec, getpid, exit, wait, close, stat,opendir, readdir.

    10

    2 Write programs using the I/O system calls of UNIXoperating system (open, read, write, etc)

    16

    3 Write C programs to simulate UNIX commands like ls, grep,

    etc.20

    4 Given the list of processes, their CPU burst times and arrivaltimes, display/print the Gantt chart for FCFS and SJF. Foreach of the scheduling policies, compute and print theaverage waiting time and average turnaround time. (2sessions)

    24

    5 Given the list of processes, their CPU burst times and arrivaltimes, display/print the Gantt chart for Priority and Roundrobin. For each of the scheduling policies, compute and printthe average waiting time and average turnaround time. (2sessions).

    32

    6 Developing Application using Inter Process Communication(using shared memory, or message queues)

    40

    7 Implement the Producer Consumer problem usingsemaphores (using UNIX system calls)

    46

    8 Implement some memory management schemes I 50

    9 Implement some memory management schemes II 58

    10 Implement any file allocation technique (Linked,Indexed or Contiguous)

    63

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    4/65

    SEC CSE/IV OS LAB MANUAL

    4

    INTRODUCTION OF THE LANGUAGE (Linux)

    MAIN FEATURES

    Linux is a generic term referring to Unix-like computer operating systems based on the

    Linux kernel. Their development is one of the most prominent examples of free and open sourcesoftware collaboration; typically all the underlying source code can be used, freely modified, and

    redistributed by anyone. The name "Linux" comes from the Linux kernel, originally written in

    1991 by Linus Torvalds. The rest of the system usually comprises components such as the Apache

    HTTP Server, the X Window System, the K Desktop Environment, and utilities and libraries from

    the GNU operating system (announced in 1983 by Richard Stallman). Many quantitative studies of

    free / open source software focus on topics including market share and reliability, with numerous

    studies specifically examining Linux. The Linux market is growing rapidly, and the revenue of

    servers, desktops, and packaged software running Linux was expected to exceed $35.7 billion by

    2008.

    ADVANTAGES

    Cost The most obvious advantage of using Linux is the fact that it is free to obtain, while

    Microsoft products are available for a hefty and sometimes recurring fee.

    Security In line with the costs, the security aspect of Linux is much stronger than that of

    Windows.

    Choice (Freedom) The power of choice is a great Linux advantage. With Linux, you

    have the power to control just about every aspect of the operating system.

    Software - There are so many software choices when it comes to doing any specific task.

    You could search for a text editor on Freshmeat and yield hundreds, if not thousands of

    results. My article on 5 Linux text editors you should know about explains how there are so

    many options just for editing text on the command-line due to the open source nature

    of Linux.

    Hardware - Linux is perfect for those old computers with barely anyprocessing power or

    memory you have sitting in your garage or basementcollecting dust .

    LIMITATIONS

    Understanding Becoming familiar with the Linux operating system requires patience as

    well as a strong learning curve. You must have the desire to read and figure things out on

    your own, rather than having everything done for you. Check out the 20 must read howtos

    and guides for Linux.

    Compatibility Because of its free nature, Linux is sometimes behind the curve when it

    comes to brand new hardware compatibility. Though the kernel contributors and

    http://www.freshmeat.net/
  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    5/65

    SEC CSE/IV OS LAB MANUAL

    5

    maintainers work hard at keeping the kernel up to date, Linux does not have as much of a

    corporate backing as alternative operating systems. Sometimes you can find third party

    applications, sometimes you cant.

    Alternative Programs Though Linux developers have done a great job at creating

    alternatives to popular Windows applications, there are still some applications that exist on

    Windows that have no equivalent Linux application. Read Alternatives to Windows

    Applications to find out some of the popular alternatives.

    APPLICATIONS

    1. OpenShot (Video editor)

    2. Apache (Web server)

    3. Firefox (Web browser)

    4. Dropbox (Online storage)

    5. Asterisk (Telephony)

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    6/65

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    7/65

    SEC CSE/IV OS LAB MANUAL

    7

    HARDWARE REQUIREMENTS

    System : 1

    O/S : Linux or Unix

    Compiler : Turbo C or TC3

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    8/65

    SEC CSE/IV OS LAB MANUAL

    8

    ABOUT THE OPERATING SYSTEM LAB

    AIM

    At the end of the course students should be able to

    describe the general structure and purpose of an operating system;

    explain the concepts of process, address space, and file; compare and contrast various CPU scheduling algorithms;

    understand the differences between segmented and paged memories, and be able todescribe the advantages and disadvantages of each;

    Compare and contrast polled, interrupt-driven and DMA-based access to I/O devices..

    OVERVIEW OF THE EXPERIMENTS

    To implement various page replacement memory management schemes to compare and

    contrast the relative performance of different page replacement schemes.

    Inter Process Communication Using Shared Memory and Message Queuescan

    communicates among them using the Shared Memory regions. Shared Memory is an

    efficient means of passing data between programs. One program will create a memory

    portion, which other processes (if permitted) can access. A shared segment can be attached

    multiple times by the same process

    The way to use the most common system calls in order to make input-output operations on

    files, as well as operations to handle files and directories in the Linux operating system.

    Implementation of FCFS and SJF Scheduling, This selects each process from the processes

    in memory that are ready to execute, and allocates the CPU to one of them using First In

    First Out and Shortest Job First Scheduling .

    LEARNING OBJECTIVES.

    The objective of this lab is to teach students about various operating systems including

    Windows, Mac and Unix. Students learn about systems configuration and administration. Students

    learn, explore and practice technologies related to mobile computing.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    9/65

    SEC CSE/IV OS LAB MANUAL

    9

    .

    GENERAL PROCEDURE FOR EXECUTING PROGRAMS

    1. Use the pico editor to create a file called hello.c containing the following lines:

    #include

    int main() {

    printf("Hello World\n");

    }

    2. Save this file. At the UNIX command prompt, invoke the gcc compiler as follows:

    gcc hello.c

    3. The result of this step (provided there are no syntax errors in the program) will be an

    Executable file called a.out. This is the default file name given by the compiler

    4. To execute the program type: ./a.out

    The period and slash in front of the a.out indicate to run the a.out file in the currentdirectory

    5. To compile a program and save the compiled version in a different file name, use the

    -o option as in: gcc -o hello.exe hello.c

    6. Note: To avoid having to put the ./ in front of the file name to execute a program, you mayadd the current directory (indicated by a period) in your PATH by typing: PATH=$PATH:.

    Note the final two characters are a full colon followed by a period

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    10/65

    SEC CSE/IV OS LAB MANUAL

    10

    EX.NO:1

    DATE:

    IMPLEMENTATION OF SYSTEM CALLS

    DESCRIPTION

    Thefork() function shall create a new process. The new process (child process) shall be anexact copy of the calling process (parent process). The child process shall have a unique

    process ID.

    The exec family of functions shall replace the current process image with a new processimage. The new image shall be constructed from regular, executable file called the new

    process image file

    The exit status will be n, if specified. Otherwise, the value will be the exit value of the lastcommand executed, or zero if no command was executed. When exitis executed in a trapaction, the last command is considered to be the command that executed immediately

    preceding the trap action

    The readdir() function returns a pointer to a dirent structure representing the next directoryentry in the directory stream pointed to by dir.

    The opendir() function opens a directory stream corresponding to the directory name, andreturns a pointer to the directory stream. The stream is positioned at the first entry in the

    directory

    OBJECTIVE

    To keep track of how many times each of the fork, vfork, execl, readdir, opendir and waitsystem

    calls is invoked

    Place counters in kernel code

    Implement a new system call providing this information

    Request/retrieve these values from user space by invoking the new system call/s

    SYNTAXES & KEYWORDS

    Fork:

    #include

    pid_t fork(void);

    execl:

    #include

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    11/65

    SEC CSE/IV OS LAB MANUAL

    11

    extern char **environ;

    int execl(const char *path, const char *arg(), /*, (char *)0 */);

    exit:

    #include

    void exit(int status);

    wait:

    #include

    #include

    pid_t wait(int *stat_loc);

    Readdir() :

    #include

    #include

    struct dirent *readdir(DIR *dir);

    Opendir():

    #include #include

    DIR *opendir(const char *name);

    HOW TO EXECUTE THE PROGRAM

    Creates New child process

    Gets the process id

    Waits until the process resumes

    Exits the program

    ADVANTAGE

    Each device can be accessed as though it was a file in the file system. Since most of the kernel

    deals with devices through this file interface, it is relatively easy to add a new device driver by

    implementing the hardware-specific code to support this abstract file interface. Therefore, this

    benefits the development of both user program code, which can be written to access devices and

    files in the same manner, and device driver code, which can be written to support a well-defined

    API.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    12/65

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    13/65

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    14/65

    SEC CSE/IV OS LAB MANUAL

    14

    Program inodeno:1815607

    Program Size :4096

    Access Time :Thu Mar 30 11:45:06 2006

    Modified Time :Tue Mar 7 10:31:36 2006Protection :33204

    User id :514

    Group id :514

    Device driverno:769

    No. of links :1

    c) opendir & readdir

    //ls command implementation using opendir & readdir //ls command implementation

    #include

    #include main(int argc,char *argv[])

    {

    DIR * dir;struct dirent *direntry; dir=opendir(argv[1]); while((direntry=readdir(dir))!=NULL)

    printf("%d %s\n",direntry->d_ino,direntry->d_name); closedir(dir);

    }

    OUTPUT:

    [cse04@LINUXSERVER vaishu]$ cc ordir.c

    [cse04@LINUXSERVER vaishu]$ ./a.out uma

    1750301 .

    3270767 ..

    1750302 aaa

    RESULT

    The program for process system call has been executed and shown the result as above.

    VIVA QUESTIONS

    1. What is an Operating system?

    An operating system is a program that manages the computer hardware. It also provides a

    basis for application programs and act as an intermediary between a user of a computer and the

    computer hardware. It controls and coordinates the use of the hardware among the various

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    15/65

    SEC CSE/IV OS LAB MANUAL

    15

    application programs for the various users.

    2. What is the use of fork and exec system calls?

    Fork is a system call by which a new process is created. Exec is also a system call, which is

    used after a fork by one of the two processes to replace the process memory space with a new

    program.

    POSSILBLE QUESTIONS

    1. Write programs using the following system calls of UNIX operating system: fork, exec, getpid, exit, wait,close, stat, opendir, readdir.

    2. Write programs using getpid, exit, wait system calls.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    16/65

    SEC CSE/IV OS LAB MANUAL

    16

    EX.NO:2

    DATE:

    IMPLEMENTATION OF I/O SYSTEM CALL

    DESCRIPTION

    File-I/O through system calls is simpler and operates at a lower level than making calls to the C

    file-I/O library. There are seven fundamental file-I/O system calls:

    creat() Create a file for reading or writing.

    open() Open a file for reading or writing.

    close() Close a file after reading or writing.

    write() Write bytes to file.

    read() Read bytes from file.

    These calls were devised for the UNIX operating system and are not part of the ANSI C spec. Use

    of these system calls requires a header file named "fcntl.h":

    SYNTAXES & KEYWORDS

    open() :

    = open( , );

    write() :

    write( , , );

    read() :

    read( , , );

    HOW TO EXECUTE THE PROGRAM

    Creates a new file

    Opens an existing fie

    Closes a file that is open

    Reads a file

    Writes the bytes of data into a file

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    17/65

    SEC CSE/IV OS LAB MANUAL

    17

    ADVANTAGE

    Each device can be accessed as though it was a file in the file system. Since most of the

    kernel deals with devices through this file interface, it is relatively easy to add a new device driver

    by implementing the hardware-specific code to support this abstract file interface. Therefore, this

    benefits the development of both user program code, which can be written to access devices and

    files in the same manner, and device driver code, which can be written to support a well-defined

    API.

    DISADVANTAGE

    The disadvantage with using the same interface is that it might be difficult to capture the

    functionality of certain devices within the context of the file access API, thereby either resulting in

    a loss of functionality or a loss of performance. Some of this could be overcome by the use of ioctloperation that provides a general purpose interface for processes to invoke operations on devices.

    APPLICATIONS

    System calls acts as entry point to OS kernel. There are certain tasks that can only be done

    if a process is running in kernel mode. Examples of these tasks can be interacting with hardware

    etc. So if a process wants to do such kind of task then it would require itself to be running in kernel

    mode which is made possible by system calls.

    ALGORITHM:

    1. Start the Program.

    2. Open a file for O_RDWR for read and write, O_CREATE for creating a file, O_TRUNC

    for truncates a file.

    3. Using getchar function, read the character and stored in the string [] array.

    4. The string [] array is write into a file and close it.

    5. Then the file is opened for read only mode and read the characters and displayed it and

    close the file.

    6. Stop the program.

    PROGRAM

    #include

    #include

    #include

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    18/65

    SEC CSE/IV OS LAB MANUAL

    18

    #include int main()

    {

    int n,i=0; int f1,f2;

    char c,strin[100]; f1=open("data",O_RDWR|O_CREAT|O_TRUNC); while((c=getchar())!='\n')

    {

    strin[i++]=c;

    }

    strin[i]='\0';

    write(f1,strin,i);

    close(f1); f2=open("data",O_RDONLY); read(f2,strin,0);

    printf("\n%s\n",strin); close(f2);

    return 0;

    }

    OUTPUT:

    [cs2002@localhost ~]$ cc isc.c

    [cs2002@localhost ~]$ ./a.out HAI

    WELCOME TO CSEHAI WELCOME TO CSE [cs2002@localhost ~]$

    RESULT

    The i/o system call program has been executed and shown the results as above.

    VIVA QUESTIONS

    1. What is a process?

    A process is a program in execution. It is the unit of work in a modern operating system. A

    process is an active entity with a program counter specifying the next instructions to execute and a

    set of associated resources. It also includes the process stack, containing temporary data and a data

    section containing global variables.

    2. What is a process state and mention the various states of a process?

    As a process executes, it changes state. The state of a process is defined in part by the

    current activity of that process. Each process may be in one of the following states: New

    Running

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    19/65

    SEC CSE/IV OS LAB MANUAL

    19

    Waiting

    Ready

    Terminated

    POSSILBLE QUESTIONS:

    1. Write programs using the I/O system calls of UNIX operating system (open, read, write,

    etc)

    2. Write programs using the I/O system call(write).

    \

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    20/65

    SEC CSE/IV OS LAB MANUAL

    20

    EX.NO:3

    DATE:

    SIMULATION OF UNIX COMMANDS

    DESCRIPTION

    ls -a

    The -a option tells the ls command to report information about all files, including hidden files.

    ls -l

    The -l option tells the "ls" command to provide a longlisting of information about the files anddirectories it reports. The long listing will provide important information about file permissions,user and group ownership, file size, and creation date

    ls -al

    This command provides a long listing of information about all files in the current directory. It

    combines the functionality of the -a and -l options. This is probably the most used version of the ls

    command.

    ls -alR /usr | more

    This command lists long information about all files in the "/usr" directory, and all sub-directories

    of /usr. The -R option tells the ls command to provide a recursive listing of all files and sub-

    directories

    ls -ld /usr

    Rather than list the files contained in the /usr directory, this command lists information about the

    /usr directory itself (without generating a listing of the contents of /usr). This is very useful when

    you want to check the permissions of the directory, and not the files the directory contains.

    SYNTAXES & KEYWORDS

    ls Command:

    ls [options] [names]

    grep Command:

    grep flag PatternList filename

    EXPECTED OUTPUT AND ITS FORM

    List the files in the directory.

    List the files of a particular user in a directory.

    List the files with its description.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    21/65

    SEC CSE/IV OS LAB MANUAL

    21

    Searches the patterns in a file

    ADVANTAGES

    Full multitasking with protected memory.

    Multiple users can run multiple programs each at the same time.

    Very efficient virtual memory, so many programs can run with a modest amount of

    physical memory.

    Access controls and security

    A rich set of small commands and utilities that do specific tasks well

    DISADVANTAGES

    The traditional command line shell interface is user hostile -- designed for the

    programmer, not the casual user.

    Commands often have cryptic names and give very little response to tell the user what

    they are doing.

    APPLICATIONS

    Commands you use in a Unix based computer OS to achieve certain things. Similar to MS/DOS

    commands in Windows. Mostly used in computers running the Linux OS.

    ALGORITHM:

    1. Start the program.

    2. Enter the options.

    3. If the option is 1call ls command and it display the files.

    4. If the option is 2 call gerp command and match the given pattern with the read word and

    if it matches, display the line of occurance.

    5. If the option is 3 call cp command.6. If the option is 4 call rm command.

    7. Stop the program.

    PROGRAM

    #include

    main()

    {

    char c; int n;

    http://wiki.answers.com/Q/What_are_the_advantages_and_disadvantages_of_Unixhttp://wiki.answers.com/Q/What_are_the_advantages_and_disadvantages_of_Unix
  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    22/65

    SEC CSE/IV OS LAB MANUAL

    22

    printf("1.list of files in the directory\n2.list the lines\n3.copy\n4.remove\n"); scanf("%d",&n);

    switch(n)

    {

    case 1: system("ls"); break;

    case 2:

    system("grep argc lsgp.c"); break;

    case 3:

    system(" cp lsgp.c gpls.c"); printf("the file is

    copied"); break;

    case 4:

    system("rm lsgp.c"); printf("the file is deleted");

    break;

    }

    }

    OUTPUT

    [it53@localhost ~]$ cc lsgp.c [it53@localhost ~]$

    ./a.out 1.list of files in the directory 2.list the lines3.copy

    4.remove

    1

    3q bit.c ftp.c ospf1.c praba.c rarp.c smp.c sort.sh

    a.out forkexec.c io.c praba1.sh praba.sh sample sorting.sh syscall.c [it53@localhost ~]$ ./a.out

    1.list of files in the directory 2.list the lines

    3.copy4.remove

    2

    system("grep argc lsgp.c"); [it53@localhost ~]$

    ./a.out 1.list of files in the directory 2.list the lines

    3.copy

    4.remove

    3the file is copied[it53@localhost ~]$ ./a.out 1.list of files in the

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    23/65

    SEC CSE/IV OS LAB MANUAL

    23

    directory

    2.list the lines 3.copy 4.remove

    4

    the file is deleted

    RESULT

    The program for simulation of unix commands ls and grep has been executed and the shownthe results as above

    VIVA QUESTIONS:

    1. Compare user threads and kernel threads.

    User threads

    User threads are supported above the Kernel threads are supported directly kernel and are

    implemented by a thread library at the user level Thread creation & scheduling are done in the user

    space, without kernel intervention. Therefore they are fast to create and manage Blocking system

    call will cause the entire process to block

    Kernel threads

    Thread creation, scheduling and management are done by the operating If the thread

    performs a blocking system call, the kernel can schedule another thread in the application for

    execution.

    2. How can a user program disrupt the normal operations of a system?

    A user program may disrupt the normal operation of a system by Issuing illegal I/O operations By

    accessing memory locations within the OS itself Refusing to relinquish the CPU

    POSSIBLE QUESTIONS:

    1. Write C programs to simulate UNIX commands like ls, grep, etc

    2. Write C programs to simulate UNIX commands like grep

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    24/65

    SEC CSE/IV OS LAB MANUAL

    24

    EX.NO:4(a)

    DATE:

    IMPLEMENTATION OF FCFS SCHEDULING

    DESCRIPTION

    The FCFS scheduler simply executes processes to completion in the order they are submitted.This code implements the First come First Served Scheduled algorithm. It gets the number of

    processes and the process name, burst time and arrival time for each user from the user. It thensorts the processes depending upon the arrival time. Calculates and displays the averageturnaround time and waiting time. Then it will display the Gantt chart.

    EXPECTED OUTPUT AND ITS FORM

    Performs FCFS scheduling ie) the process that enters the queue first is served first.

    ADVANTAGES

    simple

    easy to understand firstcome, first served

    DISADVANTAGES

    This scheduling method is nonpreemptive, that is, the process will run until it finishes.

    Because of this nonpreemptive scheduling, short processes which are at the back of thequeue have to wait for the long process at the front to finish

    ALGORITHM:

    1. Start the program.

    2. Get the number of processes and their burst time.

    3. Initialize the waiting time for process 1 is 0.

    4. The waiting time and turn around time for other processes are calculated as

    p[i].wt=p[i-1].bt+p[i-1].wt;

    p[i].tt=p[i].bt+p[i].wt;

    5. The waiting time and turn around time for all the processes are summed and then the

    average waiting time and turn around time are calculated.

    6. The average waiting time and turn around time are displayed.

    7. Stop the program.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    25/65

    SEC CSE/IV OS LAB MANUAL

    25

    PROGRAM

    #include

    #include

    #include struct process

    {

    int pid;

    int wt,tt,bt;

    }

    p[100]; void main()

    {

    int tottt,totwt,avgtt,avgwt,i,j,n; clrscr();

    printf("\nEnter Number of process"); scanf("\n%d",&n); for(i=1;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    26/65

    SEC CSE/IV OS LAB MANUAL

    26

    totwt=totwt/n;

    tottt=tottt/n;

    printf("\n\n\n\tAVGWT\tAVGTT");

    printf("\n\t%d\t%d",totwt,tottt);

    getch();

    }

    OUTPUT

    Enter Number of process3

    Enter 1st Burst Time:12

    Enter 2st Burst Time:34

    Enter 3st Burst Time:56===============================

    Process id BT WT TT

    ===============================

    1 12 0 12

    2 34 12 46

    3 56 46 102

    VGWT AVGTT

    19 53

    RESULT

    The program for first come first serve algorithm has been executed and shown the results as above.

    VIVA QUESTION

    1. What is the Kernel?

    A more common definition is that the OS is the one program running at all times on the

    computer, usually called the kernel, with all else being application programs.

    2. What are Batch systems?

    Batch systems are quite appropriate for executing large jobs that need little interaction. The user

    can submit jobs and return later for the results.

    POSSIBLE QUESTIONS:

    1. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt

    chart for FCFS

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    27/65

    SEC CSE/IV OS LAB MANUAL

    27

    DESCRIPTION

    Associate with each process the length of its next CPU burst. Use these lengths to schedule the

    process with the shortest time

    Two schemes:

    non preemptive once CPU given to the process it cannot be preempted until completes itsCPU burst

    preemptive if a new process arrives with CPU burst length less than remaining time ofcurrent executing process, preempt. This scheme is known as the Shortest-Remaining-

    Time-First (SRTF) SJF is optimal gives minimum average waiting time for a given set ofprocesses objective

    EXPECTED OUTPUT AND ITS FORM

    Performs SJF scheduling ie) the process that has the shortest burst time is processed first

    ADVANTAGES

    o simple

    o easy to understando shortest job is served

    first

    DISADVANTAGES

    Long-burst (CPU-intensive) processes are hurt with a long mean waiting time. In fact, if short-

    burst processes are always available to run, the long-burst ones may never get scheduled.

    Moreover, the effectiveness of meeting the scheduling criteria relies on our ability to estimate the

    CPU burst time.

    ALGORITHM:

    1. Start the program.

    2. Get the number of processes and their burst time.

    3. Initialize the waiting time for process 1 is 0.

    4. The processes are stored according to their burst time.

    5. The waiting time and turn around time for other processes are calculated as

    p[i].wt=p[i-1].bt+p[i-1].wt;

    EX.NO:4 (b)

    DATE:

    IMPLEMENTATION OF SJF SCHEDULING

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    28/65

    SEC CSE/IV OS LAB MANUAL

    28

    p[i].tt=p[i].bt+p[i].wt;

    6. The waiting time and turn around time for all the processes are summed and then the

    average waiting time and turn around time are calculated.

    7. The average waiting time and turn around time are displayed.Stop the program

    PROGRAM

    #include

    #include

    #include struct process

    {

    int pid;

    int wt,tt,bt;

    }

    p[100]; void main()

    {

    struct process temp;

    int tottt,totwt,avgtt,avgwt,i,j,n; clrscr();

    printf("\nEnter Number of process"); scanf("\n%d",&n); for(i=1;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    29/65

    SEC CSE/IV OS LAB MANUAL

    29

    p[i].pid=temp.pid;

    temp.bt=p[j].bt;

    p[j].bt=p[i].bt; p[i].bt=temp.bt; */ temp=p[j]; p[j]=p[i];

    p[i]=temp;} } }

    p[1].wt=0;

    p[1].tt=p[1].bt+p[1].wt;

    i=2;

    while(i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    30/65

    SEC CSE/IV OS LAB MANUAL

    30

    Enter 3 Burst Time: 7

    Enter 4 Burst Time: 2

    Enter 5 Burst Time: 9

    ===================================Process id BT WT TT

    ===================================

    4 2 0 2

    2 4 2 6

    3 7 6 13

    1 8 13 21

    5 9 21 30

    AVGWT AVGTT

    8 14

    RESULT:

    The program for shortest job first algorithm has been executed and shown the results as above.

    VIVA QUESTION:

    1. What are multiprocessor systems & give their advantages?

    Multiprocessor systems also known as parallel systems or tightly coupled systems are

    systems that have more than one processor in close communication, sharing the computer bus, the

    clock and sometimes memory & peripheral devices. Their main advantages are

    Increased throughput

    Economy of scale

    Increased reliability

    2. What is a process state and mention the various states of a process?

    As a process executes, it changes state. The state of a process is defined in part by the

    current activity of that process. Each process may be in one of the following states:

    NewRunning

    Waiting

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    31/65

    SEC CSE/IV OS LAB MANUAL

    31

    Ready

    Terminated

    POSSIBLE QUESTION:

    1 . Given the list of processes, their CPU burst times and arrival times, display/print the Ganttchart for SJF

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    32/65

    SEC CSE/IV OS LAB MANUAL

    32

    DESCRIPTION

    Each process gets a small unit of CPU time (time quantum), usually 10-100 milliseconds. After

    this time has elapsed, the process is preempted and added to the end of the ready queue.

    If there are nprocesses in the ready queue and the time quantum is q, then each process gets 1/n of

    the CPU time in chunks of at most q time units at once. No process waits more

    than (n-1)q time units.

    Performance

    q large -FIFOq small- q must be large with respect to context switch, otherwise overhead is too high

    EXPECTED OUTPUT AND ITS FORM

    Performs round robin scheduling ie) the process that is assigned with a Quantum time and the

    process is processed for the given quantum time in fcfs fashion.

    ADVANTAGES:

    simple,

    low overhead,

    works for interactive systems

    DISADVANTAGES:

    o if quantum is too small, too much time wasted in context switching

    o if too large (i.e., longer than mean CPU burst), approaches

    ALGORITHM:

    1. Start the program.

    2. Get the number of processes, their burst time and time slice for each process.

    3. Calculate the total burst time.

    4. To check whether the burst time of process is less then the time slice, the required time

    only allotted to the process.

    5. If the burst time of process is greater than the time slice one time slice is allotted for the

    process and burst time is subtracted by one time slice.

    6. Step 4 and 5 is repeated up to process burst time is 0.

    EX.NO:5(a)

    DATE:

    IMPLEMENTATION OF ROUND ROBIN SCHEDULING

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    33/65

    SEC CSE/IV OS LAB MANUAL

    33

    7. The waiting time and turn around time for all the processes are summed and then the

    average waiting time and turn around time are calculated.

    8. The average waiting time and turn around time are displayed.

    9. Stop the program.

    PROGRAM

    #include

    #include struct process

    {

    int pid,bt,tt,wt; };

    int main()

    {

    struct process x[10],p[30]; int i,j,k,tot=0,m,n;

    float wttime=0.0,tottime,a1,a2; clrscr();

    printf("\nEnter No.of process\t"); scanf("%d",&n); for(i=1;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    34/65

    SEC CSE/IV OS LAB MANUAL

    34

    {

    p[k].wt=p[k-1].tt; p[k].tt=p[k].wt+m; x[i].bt=x[i].bt-m; k++;

    } } }

    }

    printf("\nprocess id\ttwt\ttt"); for(i=1;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    35/65

    SEC CSE/IV OS LAB MANUAL

    35

    3 17 18

    Average Waiting Time: 20.000000

    Average TurnAround Time:26.000000

    RESULT:

    The program for implementation of round robin scheduling has been executed and shown theresults as above.

    VIVA QUESTION

    1. Define CPU scheduling.

    CPU scheduling is the process of switching the CPU among various processes. CPU

    scheduling is the basis of multi programmed operating systems. By switching the CPU among

    processes, the operating system can make the computer more productive.

    2. What is preemptive and non preemptive scheduling?

    Under non preemptive scheduling once the CPU has been allocated to a process, the

    process keeps the CPU until it releases the CPU either by terminating or switching to the waiting

    state. Preemptive scheduling can preempt a process which is utilizing the CPU in between its

    execution and give the CPU to another process.

    POSSIBLE QUESTION:

    1. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt

    chart for Round robin.2. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt

    chart for Round robin. , compute and print the average waiting time and average

    turnaround time

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    36/65

    SEC CSE/IV OS LAB MANUAL

    36

    DESCRIPTION

    A priority number (integer) is associated with each process

    The CPU is allocated to the process with the highest priority (smallest integer highest priority)

    - Preemptive

    - non preemptive

    SJF is a priority scheduling where priority is the predicted next CPU burst time

    Problem Starvation low priority processes may never execute

    Solution Aging as time progresses increase the priority of the process

    Performs priority scheduling ie) the process that is assigned with a highest priority is processed

    first.

    ADVANTAGES:

    simple,

    low overhead,

    works for interactive systems

    DISADVANTAGES:

    The job remains in the queue for a long time.

    ALGORITHM:

    1. Start the program.

    2. Get the number of processes, their burst time and priority.

    3. Initialize the waiting time for process 1 is 0.4. Based upon the priority processes are arranged.

    5. The waiting time and turn around time for other processes are calculated as

    p[i].wt=p[i-1].bt+p[i-1].wt;

    p[i].tt=p[i].bt+p[i].wt;

    6. The waiting time and turn around time for all the processes are summed and then the

    average waiting time and turn around time are calculated.

    7. The average waiting time and turn around time are displayed.

    8. Stop the program.

    EX.NO:5(b)

    DATE:

    IMPLEMENTATION OF PRIORITY SCHEDULING

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    37/65

    SEC CSE/IV OS LAB MANUAL

    37

    PROGRAM:

    #include

    #include

    #include struct process

    {

    int pid;

    int wt,tt,bt,prior;

    }

    p[100],temp; void main()

    {

    int tottt,totwt,avgtt,avgwt,i,j,n; clrscr();

    printf("\nEnter Number of process"); scanf("\n%d",&n); for(i=1;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    38/65

    SEC CSE/IV OS LAB MANUAL

    38

    totwt=tottt=0;

    i=1;

    printf("\n\t===============================");

    printf("\n\tPSSID\tBT\tWT\tTT");printf("\n\t===============================");

    while(i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    39/65

    SEC CSE/IV OS LAB MANUAL

    39

    ===============================

    PSSID BT WT TT

    ===============================

    15 0 5

    2 7 5 12

    3 8 12 20

    AVGWT AVGTT

    5 12

    RESULT

    The program for priority scheduling has been executed and shown the results as above.

    VIVA QUESTION:

    1. Define throughput?

    Throughput in CPU scheduling is the number of processes that are completed per unit time.

    For long processes, this rate may be one process per hour; for short transactions, throughput might

    be 10 processes per second.2. What is turnaround time?

    Turnaround time is the interval from the time of submission to the time of completion of a

    process. It is the sum of the periods spent waiting to get into memory, waiting in the ready queue,

    executing on the CPU, and doing I/O

    POSSIBLE QUESTION:

    1. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt

    chart for Priority Scheduling.

    2. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt

    chart for Priority Scheduling. compute and print the average waiting time and average

    turnaround time

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    40/65

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    41/65

    SEC CSE/IV OS LAB MANUAL

    41

    6. The data in the shared memory is read by the child process using the shnot pointer

    7. Now, detach and rebase the shared memory

    8. Stop the program

    PROGRAM:

    #include

    #include

    #include

    main()

    {

    int shmid;

    key_t key=0*10; shmid=shmget(key,100,IPC_CREAT|0666); if(shmid

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    42/65

    SEC CSE/IV OS LAB MANUAL

    42

    results as above.

    VIVA QUESTION:

    1.What is process control block?

    Each process is represented in the operating system by a process

    It contains the following information:

    Process state

    Program counter

    CPU registers

    CPU-scheduling information

    Memory-management information

    Accounting information I/O

    status information

    2. What are the use of job queues, ready queues & device queues?

    As a process enters a system, they are put into a job queue. This queue consists of all jobs in the

    system. The processes that are residing in main memory and are ready & waiting to execute are

    kept on a list called ready queue. The list of processes waiting for a particular I/O device is kept in

    the device queue

    POSSIBLE QUESTION:

    1. Developing Application using Inter Process Communication using shared memory)

    2. Developing Application using Inter Process Communication using message queues)

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    43/65

    SEC CSE/IV OS LAB MANUAL

    43

    DESCRIPTION

    Using pipes for establishing a communication between two processes. As a first step we

    need to identify two executables that need to communicate. As an example, consider a case where

    one process gets a character string input and communicates it to the other process which reverses

    strings. Then we have two processes which need to communicate. Next we define a pipe and

    connect it between the processes to facilitate communication. One process gets input strings and

    writes into the pipe. The other process, which reverses strings, gets its input (i.e. reads) from the

    pipe.

    Figure explains how the pipes are used. As shown in the upper part of the figure, a pipe has

    an input end and an output end. One can write into a pipe from the input end and read from the

    output end. A pipe descriptor, therefore, has an array that stores two pointers. One pointer is for its

    input end and the other is for its output end. When a process defines a pipe it gets both the

    addresses, as shown in the middle part of Figure. Let us suppose array pp is used to store the

    descriptors. pp[0] stores the write end address and pp[1] stores the read end address. Suppose two

    processes, Process A and Process B, need to communicate, then it is imperative that the process

    which writes closes its read end of the pipe and the process which read closes its write end of the

    pipe. Essentially, for a communication from Process A to process B the following should happen.

    Process A should keep its write end open and close read end of the pipe. Similarly, Process B

    should keep its read end open and close its write end.

    EXPECTED OUTPUT AND ITS FORM

    To use these pipes, we will write two program's one to represent the server and other to represent

    the client. The server will read from the pipe fifo_server to which the client will send a request. On

    receiving the request, the server will send the information to the client on fifo_client.

    ADVANTAGES:

    Speed of communication

    This method is available on any platform (Windows 95/98 as well as Windows NT).

    EX.NO:6(b)

    DATE:

    IMPLEMENTATION OF PRIORITY SCHEDULING

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    44/65

    SEC CSE/IV OS LAB MANUAL

    44

    DISADVANTAGES:

    Synchronizing access

    security

    ALGORITHM:1. Start the program.

    2. Create the child process using fork().

    3. Create the pipe structure using pipe().

    4. Now close the read end of the parent process using close().

    5. Write the data in the pipe using write().

    6. Now close the write end of child process using close().

    7. Read the data in the pipe using read().

    8. Display the string.

    9. Stop the program.

    PROGRAM:

    #include

    main()

    {

    int fd[3],pid;

    char *msg=("OS LAB\n"); char buff[25];

    pipe(fd);

    pid=fork();

    if(pid==0)

    {

    puts("child process\n"); close(fd[0]); write(fd[1],msg,30);

    }

    else

    {

    sleep(1);

    puts("parent process\n"); close(fd[1]); read(fd[0],buff,30); printf("%s",buff);

    }

    }

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    45/65

    SEC CSE/IV OS LAB MANUAL

    45

    OUTPUT:

    [cse2@localhost ~]$ cc pipe.c

    [cse2@localhost ~]$ ./a.out child

    process

    parent process

    OS LAB

    [cse2@localhost ~]$

    RESULT

    The program for interprocess communication using pipe process has been executed and shown

    results as above

    VIVA QUESTION:

    What are the various file operations?

    The six basic file operations are

    Creating a file

    Writing a file

    Reading a file

    Repositioning within a file

    Deleting a fileTruncating a file

    2. What are the information associated with an open file?

    Several pieces of information are associated with an open file which may be:

    File pointer

    File open count

    Disk location of the file Accessrights

    Possible Question:

    1 Developing Application using Inter Process Communication (using shared memory, or message queues)

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    46/65

    SEC CSE/IV OS LAB MANUAL

    46

    DESCRIPTION

    This is an illustration of a solution to the classic producer-consumer (bounded-buffer) problem

    using semaphores.

    CONCEPT Producers produce items to be stored in the buffer. Consumers remove and consume

    items which have been stored. Mutual exclusion must be enforced on the buffer itself. Moreover,

    producers can store only when there is an empty slot, and consumers can remove only when there

    is a full slot. Three semaphores are used. The binary semaphore mutex controls access to the buffer

    itself. The counting semaphore empty keeps track of empty slots, and the counting semaphore fullkeeps track of full slots. In this example, the buffer is implemented as an array of size MAX

    treated as a circular (ring) buffer. Variables in and out give the index of the next position for

    putting in and taking out (if any). Variable count gives the number of items in the buffer.

    EXPECTED OUTPUT AND ITS FORM

    one or more producers are generating data and placing these in a buffer

    a single consumer is taking items out of the buffer one at time

    only one producer or consumer may access the buffer at any one time

    ADVANTAGES:

    Effective resource utilization

    DISADVANTAGES:

    A semaphore does not keep track of which of the resources are free.

    This includes:

    Requesting a resource and forgetting to release it releasing aresource that was never requested holding a resource for along time without needing itusing a resource without requesting it first (or after releasing it).

    ALGORITHM:

    1. Start the program.

    2. Declare the variables in the type of pthread_t as tid_produce tid_consume.

    3. Declare a structure for semaphore variables.

    EX. NO: 7PRODUCER-CONSUMER PROBLEM USING SEMAPHORES.DATE:

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    47/65

    SEC CSE/IV OS LAB MANUAL

    47

    4. During run time read the number of items to be produced and consumed.

    5. Declare and define semaphore function for creation and destroy.

    6. Define producer function.

    7. Define consumer function.8. Call producer and consumer function.

    9. Stop the execution.

    PROGRAM:

    #include #include

    #include #define NBUFF 10

    int nitems; struct {

    int buff[NBUFF];

    sem_t mutex, nempty, nstored; } shared;

    void *produce (void *); void *consume (void *);

    int main(int argc, char **argv)

    {

    pthread_t tid_produce, tid_consume; if(argc !=2)

    {printf("Useage: filename "); return 0;

    }

    printf ("\n\n Producer - Consumer Problem using Semaphore\n"); printf (" --------------------

    -----------------------\n\n"); nitems=atoi(argv[1]);

    sem_init(&shared.mutex,0,1); sem_init(&shared.nempty,0,NBUFF);

    sem_init(&shared.nstored,0,0); pthread_setconcurrency(2);

    pthread_create(&tid_produce,NULL,produce,NULL);pthread_create(&tid_consume,NULL,consume,NULL);

    pthread_join(tid_produce,NULL); pthread_join(tid_consume,NULL);

    sem_destroy(&shared.mutex);

    sem_destroy(&shared.nempty);

    sem_destroy(&shared.nstored);

    }

    void *produce (void *arg)

    {

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    48/65

    SEC CSE/IV OS LAB MANUAL

    48

    int i; for(i=0;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    49/65

    SEC CSE/IV OS LAB MANUAL

    49

    Producer.....buff[0] = 0

    Consumer.....buff[0] = 0

    Producer.....buff[1] = 1

    Consumer.....buff[1] = 1

    Producer.....buff[2] = 2

    Consumer.....buff[2] = 2

    Producer.....buff[3] = 3

    Consumer.....buff[3] = 3

    RESULT

    The program to implement producer and consumer problem using semaphores has been

    executed and shown the results as above.

    VIVA QUESTION:

    1. What is semaphores?

    A semaphore S is a synchronization tool which is an integer value that, apart from

    initialization, is accessed only through two standard atomic operations; wait and signal.

    Semaphores can be used to deal with the n-process critical section problem. It can be also used to

    solve various synchronization problems.

    The classic definition of wait

    wait (S)

    { }while (S

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    50/65

    SEC CSE/IV OS LAB MANUAL

    50

    2. Define deadlock prevention.Deadlock prevention is a set of methods for ensuring that at least one of the four necessary

    conditions like mutual exclusion, hold and wait, no pre- emption and circular wait cannot hold. By

    ensuring that that at least one of these conditions cannot hold, the occurrence of a deadlock can be

    prevented.

    3. Define deadlock avoidance.

    An alternative method for avoiding deadlocks is to require additional information about how

    resources are to be requested. Each request requires the system consider the resources currently

    available, the resources currently allocated to each process, and the future requests and releases of

    each possible future deadlock.

    POSSIBLE QUESTION:

    1. Implement the Producer Consumer problem using semaphores (using UNIX system

    calls).

    2. Implement the Producer Consumer problem using UNIX system calls.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    51/65

    SEC CSE/IV OS LAB MANUAL

    51

    DESCRIPTION

    Memory Management Algorithms

    In an environment that supports dynamic memory allocation, the memory manager must keep a

    record of the usage of each allocatable block of memory. This record could be kept by using

    almost any data structure that implements linked lists. An obvious implementation is to define a

    free list of block descriptors, with each descriport containing a pointer to the next descriptor, a

    pointer to the block, and the length of the block. The memory manager keeps a free list pointer and

    inserts entries into the list in some order conducive to its allocation strategy. A number of

    strategies are used to allocate space to the processes that are competing for memory .

    First Fit

    Another strategy is first fit, which simply scans the free list until a large enough hole is found.

    Despite the name, first-fit is generally better than best-fit because it leads to less fragmentation.

    Small holes tend to accumulate near the beginning of the free list, making the memory allocator

    search farther and farther each time.Solution:Next Fit

    Best Fit

    The allocator places a process in the smallest block of unallocated memory in which it will fit. It

    requires an expensive search of the entire free list to find the best hole. More importantly, it leads

    to the creation of lots of little holes that are not big enough to satisfy any requests. This situation is

    calledfragmentation, and is a problem for all memory-management strategies, although it is

    EXPECTED OUTPUT AND ITS FORM

    The memory segments are allocated with the memory space using First fit and Best Fit techniques.

    ADVANTAGES:

    effective memory utilization

    EX NO : 8MEMORY MANAGEMENT SCHEMES I

    FIRST FIT BEST FIT

    DATE:

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    52/65

    SEC CSE/IV OS LAB MANUAL

    52

    DISADVANTAGES:

    First fit wastes memory space Best Fit more time consuming suffer from external fragmentation

    ALGORITHM:

    1. Start the program.

    2. Get the number of segments and size.

    3. Get the memory requirement and select the option.

    4. If the option is 2 call first fit function.

    5. If the option is 1 call best fit function.

    6. Otherwise exit.

    7. For first fit, allocate the process to first possible segment which is free.

    8. For best fit, do the following steps.

    a. Sorts the segments according to their sizes.

    b. Allocate the process to the segment which is equal to or slightly greater than the

    process size.

    9. Stop the program.

    PROGRAM:

    #include

    #include #define MAXSIZE 25 void printlayout(int[],int ); int

    firstfit(int[],int, int); int bestfit(int[],int, int); void main()

    {

    int i,a[25],n,req,choice,pos,ch; clrscr();

    printf("How MAny Segments"); scanf("%d",&n); for(i=0;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    53/65

    SEC CSE/IV OS LAB MANUAL

    53

    {

    case 1: pos=bestfit(a,n,req); break;

    case 2: pos=firstfit(a,n,req);

    break;

    }

    printf("\tBestfit and Firstfit Algorithm\n"); printf("\t______________________________\n\n");

    printlayout(a,n);

    printf("Your Memory Requirment is :%d\n\n",req); printf("Alloted Memory Region

    is:%d\n\n",a[pos]); a[pos]=0;

    printf("Do You Want To Continue 1/0"); scanf("%d",&ch);

    if(ch==1) goto loop; getch();

    }

    void printlayout(int a[],int n)

    {

    int i,j;

    printf("\t\tMemory Free List"); printf("\n\t\t_______________\n\n");

    printf("\t\t|~~~|\n");

    for(i=0;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    54/65

    SEC CSE/IV OS LAB MANUAL

    54

    int b[25],i,j,temp,val; for(i=0;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    55/65

    SEC CSE/IV OS LAB MANUAL

    55

    | |

    | |

    | |

    | ||500| | --- |

    | |

    | |

    |200| | --- |

    | |

    | |

    | ||300|| --- |

    | |

    | |

    | |

    |

    |400| | --- |

    Your Memory Requirment is :200

    Alloted Memory Region is:200

    Do You Want To Continue 1/0 1

    How Much Is Your Memory Requirment250

    1.Bestfit

    2.Firstfit

    3.Exit

    Enter Your Choice 1

    Bestfit and Firstfit Algorithm

    Memory Free List

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    56/65

    SEC CSE/IV OS LAB MANUAL

    56

    |~~~|

    | |

    | |

    | ||500|

    Your Memory Requirment is :250

    Alloted Memory Region is:300

    Do You Want To Continue 1/0

    0

    RESULT

    The program for best fit and first fit algorithm for memory management has been executed

    and shown the results as above.

    VIVA QUESTION:

    1. What is the main function of the memory-management unit?

    The runtime mapping from virtual to physical addresses is done by a hardware device

    called a memory management unit (MMU).

    2. What are the common strategies to select a free hole from a set of available holes?

    The most common strategies are

    a. First fit

    b. Best fit

    c. Worst fit

    3. What is virtual memory?

    Virtual memory is a technique that allows the execution of processes that may not be

    completely in memory. It is the separation of user logical memory from physical memory. This

    separation provides an extremely large virtual memory, when only a smaller physical memory isavailable.

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    57/65

    SEC CSE/IV OS LAB MANUAL

    57

    POSSIBLE QUESTION:

    1. Implement some memory management schemes I

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    58/65

    SEC CSE/IV OS LAB MANUAL

    58

    DESCRIPTION

    Page replacement algorithms are used to decide what pages to page out when a page needs to beallocated. This happens when a page fault occurs and free page cannot be used to satisfy allocation

    FIFO:

    The frames are empty in the beginning and initially no page fault occurs so it is set to minus

    one. When a page fault occurs the page reference string is brought into memory. The operating

    system keeps track of all the pages in memory, herby keeping track of the most recently arrived

    and the oldest one. If the page in the page reference string is not in memory, the page fault is

    incremented and the oldest page is replaced. If the page in the page reference string is in the

    memory, take the next page without calculating the page fault. Take the next page in the page

    reference string and check if the page is already present in the memory or not. Repeat the process

    until all the pages are referred and calculate the page fault for all those pages in the page reference

    string for the number of available frames.

    LRU :

    A good approximation to the optimal algorithm is based on the observation that pages that have

    been heavily used in the last few instructions will probably be heavily used again in the next few.

    Conversely, pages that have not been used for ages will probably remain unused for a long time.

    This idea suggests a realizable algorithm: when a page fault occurs, throw out the page that has

    been unused for the longest time. This strategy is called LRU (Least Recently Used) paging

    EXPECTED OUTPUT AND ITS FORM

    Minimizing the number of (major) page faults (situations where a page must be brought in from

    disk) using LRU and FIFO.

    ADVANTAGES:

    effective memory utilization

    DISADVANTAGES:

    Time consuming

    EX.NO: 9

    DATE:

    MEMORY MANAGEMENT SCHEMES II

    PAGE REPLACEMENT

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    59/65

    SEC CSE/IV OS LAB MANUAL

    59

    ALGORITHM:

    1. Start the program

    2. Obtain the number of sequences, number of frames and sequence string from the user3. Now when a page is not in the frame comes, increment the number of page fault and

    remove the page that come in the first in FIFO algorithm

    4. In LRU algorithm, when a page fault occurs, the page which most recently used is

    removed

    5. Display the number of faults

    Stop the program

    PROGRAM:

    #include

    int m,n,i,j,k,flag,count=0,refer[100],page_frame[100][2],fault=0,min,no_frames; void replace(int z)

    {

    for(i=0;i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    60/65

    SEC CSE/IV OS LAB MANUAL

    60

    page_frame[k][1]=++count;

    for(j=0;j

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    61/65

    SEC CSE/IV OS LAB MANUAL

    61

    OUTPUT:

    Enter the number of reference:10

    Enter the number of frames:3

    Enter the reference string:7 0 1 2 0 3 0 4 2 6

    FIFO ALGORITHM

    7 -1 -1

    7 0 -1

    7 0 1

    2 0 1

    no page fault 2 3 1 2 3 0 4 3 0 4 2 0 4 2 6

    number of page fault is:9

    LRU ALGORITHM

    7 -1 -1

    7 0 -1

    7 0 1

    RESULT:

    The program for page replacement algorithms for memory management has been executed andshown the results as above.

    VIVA QUESTION:

    1. What is Demand paging?

    Virtual memory is commonly implemented by demand paging. In demand paging, thepager brings only those necessary pages into memory instead of swapping in a whole process.

    Thus it avoids reading into memory pages that will not be used anyway, decreasing the swap time

    and the amount of physical memory needed.

    2. What are the various page replacement algorithms used for page replacement?

    FIFO page replacement

    Optimal page replacement

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    62/65

    SEC CSE/IV OS LAB MANUAL

    62

    LRU page replacement

    LRU approximation page replacement

    Counting based page replacement

    Page buffering algorithm.

    POSSIBLE QUESTION:

    1. Implement some memory management schemes II

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    63/65

    SEC CSE/IV OS LAB MANUAL

    63

    DESCRIPTION

    File Allocation Methods

    One main problem in file management is how to allocate space for files so that disk space isutilized effectively and files can be accessed quickly. Three major methods of allocating diskspace are:* Contiguous Allocation* Linked Allocation

    * Indexed Allocation.Each method has its advantages and disadvantages. Accordingly, some systems support all three(e.g. Data General's RDOS). More commonly, a system will use one particular method for all files.

    Contiguous File Allocation

    Each file occupies a set of contiguous block on the diskAllocation using first fit/best fit.A need for compaction

    Only starting block and length of file in blocks are needed to work with the fileAllows random access

    Problems with files that grow

    EXPECTED OUTPUT AND ITS FORM

    Allocates blocks of memory for files using file allocation techniques.

    ADVANTAGES:

    effective memory utilization

    each file occupies set of contiguous blocks on the disk. Random access

    DISADVANTAGES:

    Time consuming

    Wastes lot of memory space

    EX.NO: 10

    DATE:

    FILE ALLOCATION TECHNIQUE-CONTIGUOUS

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    64/65

    SEC CSE/IV OS LAB MANUAL

    64

    ALGORITHM:

    1. Start the process

    2. Declare the necessary variables

    3. Get the number of files

    4.Get the total no. of blocks that fit in to the file

    5. Display the file name, start address and size of the file. 6.Stop the program

    PROGRAM:

    #include void main()

    {

    int i,j,n,block[20],start: printf(Enter the no. of file:\n);

    scanf(%d,&n);

    printf(Enter the number of blocks needed for each file:\n); for(i=0,i

  • 8/12/2019 Final Copy OSlab Manua1. Jjjjjjjjjjj 2

    65/65

    SEC CSE/IV OS LAB MANUAL

    File 3 8 6

    File 4 14 1

    RESULT:

    The program for file allocation technique has been executed and shown the results as above.

    VIVA VOICE

    1. What are the allocation methods of a disk space?

    Three major methods of allocating disk space which are widely in use are

    a. Contiguous allocation

    b. Linked allocation

    c. Indexed allocation

    2. What is Directory?

    The device directory or simply known as directory records information- such as name,

    location, size, and type for all files on that particular partition. The directory can be viewed as a

    symbol table that translates file names into their directory entries.

    Search for a fileCreate a file

    Delete a file

    Rename a file

    List directory

    Traverse the file system

    POSSIBLE QUESTION:

    1. Implement any file allocation technique (Linked, Indexed or Contiguous)