Sunteți pe pagina 1din 68

COMPUTER LABORATORY MANUAL

Operating System
(CS 330)
Fall Semester

DEPARTMENT OF COMPUTER SOFTWARE ENGINEERING


Military College of Signals
National University of Sciences and Technology
www.mcs.nust.edu.pk

CS 330 Operating Systems Introduction to Operating Systems

PREFACE
This lab manual has been prepared to facilitate the students of software engineering in studying and analysing
various components of an operating system. Operating system is a software component that allows the users to
interact with the hardware and also hides the underlying complexity. This lab manual is designed to give
practice to the students in using and manipulating different OS. The OS constructs are simulated as well. The
platforms are Windows and Linux. Tools and language required are highlighted in each session.

PREPARED BY
Lab manual is prepared by Dr. Hammad Afzal and Lab Engr Umar Mahmud under the supervision of Head of
Department Dr. Naveed Iqbal Rao in year 2012.

GENERAL INSTRUCTIONS
a. Students are required to maintain the lab manual with them till the end of the semester.
b. All readings, answers to questions and illustrations must be solved on the place provided. If more space is
required then additional sheets may be attached.
c. It is the responsibility of the student to have the manual graded before deadlines as given by the instructor
d. Loss of manual will result in re submission of the complete manual.
e. Students are required to go through the experiment before coming to the lab session. Lab session details will
be given in training schedule.
f. Students must bring the manual in each lab.
g. Keep the manual neat clean and presentable.
h. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarised and no re submission
will be entertained.
i. Marks will be deducted for late submission.

Date

Version

September 2012
August 2014
August 2015

1.0
1.1
1.2

VERSION HISTORY
Updated By
LE Umar Mahmud
Lec Mobeena Shahzad
Lec Mobeena Shahzad

Details

First Version Created


Updated Experiment 4 and Experiment 5
CLOs defined with each experiment

CS 330 Operating Systems Introduction to Operating Systems

Mapping of CLOs to Lab Experiments

1
2
3
4
5
6
7
8
9
10
11
12
13
14

List of Experiments
Introduction to Operating Systems
Ubuntu
Creating Process using C++
Creating process in Ubuntu and Windows
Creating Process using Java
Process State Model
Threads
Process Scheduling
Petersons Algorithm
Semaphores
Linux Modules
IPC
MLFQ
Memory Management

CS 330 Operating Systems Introduction to Operating Systems

CLO
1
1
2
2
2
2
2
2
2
3
2
3
3
3

MARKS
Ex
p#

Date
Conducted

Experiment Title

Max.
Marks

1
2
3
4
5
6
7
8
9
10
11
12
13
14

Grand Total

CS 330 Operating Systems Introduction to Operating Systems

Marks
Obtaine
d

Instructor
Sign

LIST OF EXPERIMENTS
EXPERIMENT 1 INTRODUCTION TO OPERATING SYSTEMS.................................................................6
EXPERIMENT 2 UBUNTU................................................................................................................. 9
EXPERIMENT 3 CREATING PROCESS USING C++..............................................................................13
EXPERIMENT 4 CREATING PROCESS IN UBUNTU AND WINDOWS.....................................................16
EXPERIMENT 5 CREATING PROCESS USING JAVA............................................................................ 20
EXPERIMENT 6 PROCESS STATE MODEL......................................................................................... 23
EXPERIMENT 7 THREADS.............................................................................................................. 25
EXPERIMENT 8 PROCESS SCHEDULING.......................................................................................... 27
EXPERIMENT 9 PETERSONS ALGORITHM...................................................................................... 29
EXPERIMENT 10 SEMAPHORES...................................................................................................... 31
EXPERIMENT 11 LINUX MODULES................................................................................................. 33
EXPERIMENT 12 IPC...................................................................................................................... 36
EXPERIMENT 13 MLFQ.................................................................................................................. 38
EXPERIMENT 14 MEMORY MANAGEMENT..................................................................................... 41

CS 330 Operating Systems Introduction to Operating Systems

EXPERIMENT 1 INTRODUCTION TO OPERATING SYSTEMS


1.

5.

Objectives:
(a). Practical usage of different OS.
(b). Working with common system tools in Windows and Ubuntu
Time Required: 3 hrs
Software Required:
(a). MS DOS
(b). Windows OS
(c). Ubuntu OS
(d). Android/Symbian/etc
Operating System is an intermediary between the user of a compute machine and the underlying
hardware. The major need of an OS is to provide a convenient means to the user for machine
operation. Moreover, the OS also solves the user problems as well as hides the complexities of
the underlying hardware.
Components of the OS are shown as below

6.

Which Operating Systems have you used? Enlist.

(0.5)

7.

Is Symbian an OS? Where is it used?

(0.25)

8.

Is Android an OS? Where is it used?

(0.25)

9.
10.

Disk Operating System (DOS): DOS is a single task batch OS. It has a Command-Line
Interface (CLI) that allows the user to perform different tasks. DOS was developed for IBM
compatible machines in 1981.
Press Windows key + r and type cmd. What was the outcome?

(0.25)

11.

Type HELP to view a list of commands.

2.
3.

4.

CS 330 Operating Systems Introduction to Operating Systems

12.
13.
14.
15.

Use the TIME command to set the new time.


Set the title to your name using the TITLE command
Is DOS Case-Sensitive? (True/False)
Do DOS allow two tasks to be done simultaneously? Give comments?

(0.25)
(0.5)

16.

Type CALC. What is the outcome?

(0.25)

17.

What happens when we type IPCONFIG? What happens when IPCONFIG/ALL is typed?

(0.25)

18.
19.
20.

22.

A list of DOS commands can be found here. http://www.computerhope.com/msdos.htm


Windows is a graphical, multi-tasking OS developed by Microsoft since 1985.
Task Manager: Open the task manager and enlist what all information is shown. Write the titles
of the tabs and the information provided under these tabs. Show the PID for each process in the
Processes Tab.
Processes: A Process is a program in execution. A program is a combination of code and data.
The programs that you may be familiar with have only one process. Programs that hold multiple
processes can be written e.g., a program that opens a file on a disk, reads the data and sends it to
a receiver through the internet can have the Reading Process and the Sending Process.
Terminate the process WINWORD.EXE. What was the effect?

(0.5)

23.

In the Performance Tab, What are the current CPU usage and the PF Usage?

(0.25)

24.

In the users tab? Who all are the current users? Can users be switched in windows? If so how?

(0.5)

25.

What is the total number of Handles, Threads and Processes currently on your machine? Where
did you find it?

(0.5)

26.

Disk Manager: Right click on My Computer and select Manage. Go to storage and then Disk
Management. What is displayed?

(0.25)

27.

Disk Defragmenter: Check to see which disks need to be defragmented?

(0.25)

28.

Device Manager: Select device manager. Disable and then Enable the sound driver. What
facility is provided in Device Manager?

(0.5)

21.

CS 330 Operating Systems Introduction to Operating Systems

(1)

29.

What are the specifications of your mobile phone? Write the Make, Model, and the OS.

(0.25)

30.

Describe how can you get the MAC address of your mobile phone? Write the
command/procedure and the MAC address

(0.5)

31.
32.
33.

Ubuntu: Ubuntu is a free, open-source, graphical, multi-tasking Linux-distribution.


Install Ubuntu on your private-machine
System Monitor: This tool is the equivalent of task manager in windows. Identify what all
information is displayed in System Monitor.

34.

Which is better System Monitor or Task Manager? Give your thoughts.

35.

Use the Device Manager in Ubuntu. Disable and Enable the Sound Driver. What facility is
provided in Device manager?

35.

What did you learn in this experiment?

36.

Web Resources:
A list of DOS commands can be found here. http://www.computerhope.com/msdos.htm
More information about linux at http://www.liberiangeek.net/2010/03/linux-beginner-anintroduction-to-ubuntu-linux/
More info on using Ubuntu Terminal https://help.ubuntu.com/community/UsingTheTerminal and
http://linuxpoison.blogspot.com/2008/10/useful-commands-in-ubuntu.html Further Guide
can be found here http://ubuntuguide.org/wiki/Ubuntu_Precise
Video Resources
http://www.youtube.com/watch?v=VuV8aR2D5Gs
http://www.youtube.com/watch?v=1FJHYqE0RDg
http://www.youtube.com/watch?v=MaA0vFKt-ew

37.

Summary:

CS 330 Operating Systems Introduction to Operating Systems

(0.5)

(1)

(0.5)

(1)

In this experiment we have learned how to use different operating systems (Windows, Ubuntu) and how to use
their tools.

CS 330 Operating Systems Introduction to Operating Systems

EXPERIMENT 2 UBUNTU
1.

2.
3.
4.

5.

Objectives:
(a). Using Ubuntu and beginners tasks in Ubuntu
(b). Using Terminal Commands in Ubuntu. Setting up Proxy and Network in Ubuntu.
(c). Creating Java codes in Ubuntu and analysing Java codes over multiple platforms.
Time Required: 3 hrs
Software Required:
(a). Ubuntu OS/Windows OS
(b). NetBeans 7.2
Change Themes: Change the theme.
(a). Right-click on the desktop and select change desktop background
(b). Select a Wall paper that best describe you. What is the name of the image?
______________________________________
(c). Change the Theme.
Updating Software: Go to System Settings and then Software Sources
(a). On the Ubuntu Software tab is where you specify Ubuntu Software Sources. All software
from Ubuntu is stored in this location. Select the check boxes to enable. If you need to
add software from other sources, select other.

(b). On the Updates tab, check the types of updates to install. The first two are recommended.
You can also choose to alert you when theres a new upgrade available by choosing
Normal releases in the Release upgrade option.

More
information
at
introduction-to-ubuntu-linux/
10

http://www.liberiangeek.net/2010/03/linux-beginner-an-

CS 330 Operating Systems UBUNTU

(1)

6.

7.

Establish Network and Proxy: You need to know the IP of the system you are using from
Windows.
(a). Go to Windows, Select Run, Type cmd. Type IPCONFIG/all. Write the IP of your
machine here; ___________________
(b). In Ubuntu Go to System Settings and then Network. In Wired tab select Configure. Type
Connection Name as CSDept.
(c). Under IPv4 Settings, Add under address your IP, Netmask is 255.255.252.0, Gateway is
172.23.19.250
(d). DNS Servers are 172.23.16.1 and 172.23.5.12
(e). Select Save.
(f). Which is the browser provided with Ubuntu? ____________________
(g). Open FireFox, Go to Edit and Preferences.
(h). In Network Tab , Select Settings
(i). Type Manual Proxy as 192.168.50.10 and port 8080
(j). Check the Internet and write the top news at www.bbc.com here
__________________________________
(k). Downloads this experiment document from LMS.
(l). Note: This configuration only works in MCS.
(m). Help can be found here http://www.howtogeek.com/howto/17012/how-to-find-your-ipaddress-in-ubuntu/
Using Terminal: Terminal is Command Line Interface of Ubuntu.
(a). Methods to load terminal are : (1)
Dash -> Search for Terminal
(2)
Dash -> More Apps -> 'See More Results' -> Terminal
(3)
Dash -> More Apps -> Accessories -> Terminal
(4)
Keyboard Shortcut: Ctrl + Alt + T
(5)
Type help to view commands
(6)
What is the CLI interface provided in Windows? _________________
(b). File and Directory Commands
(7)
The tilde (~) symbol stands for your home directory. If you are user, then the tilde
(~) stands for /home/user
(8)
pwd: The pwd command will allow you to know in which directory you're
located (pwd stands for "print working directory").
(9)
ls: The ls command will show you ('list') the files in your current directory. Used
with certain options, you can see sizes of files, when files were made, and
permissions of files.
(10)
cd: The cd command will allow you to change directories.
(11)
cp: The cp command will make a copy of a file for you. Example: "cp file foo"
will make an exact copy of "file" and name it "foo", but the file "file" will still be
there. If you are copying a directory, you must use "cp -r directory foo".
(12)
mv: The mv command will move a file to a different location or will rename a
file.
(13)
rm: Use this command to remove or delete a file in your directory.
(14)
rmdir: The rmdir command will delete an empty directory.
(15)
mkdir: The mkdir command will allow you to create directories.
(16)
sudo: The sudo command is used to perform file operations on files that the Root
User would only be allowed to change.
11

CS 330 Operating Systems UBUNTU

8.

9.
10.
11.
12.

(c). System Information Commands


(17)
df: The df command displays filesystem disk space usage for all mounted
partitions.
(18)
du: The du command displays the disk usage for a directory. It can either display
the space used for all subdirectories or the total for the directory you run it on.
Example:
(19)
ip addr reports on your system's network interfaces.
Type ifconfig in terminal. What does ifconfig show?

(1)

More info here https://help.ubuntu.com/community/UsingTheTerminal


and http://linuxpoison.blogspot.com/2008/10/useful-commands-in-ubuntu.html Further Guide
can be found here http://ubuntuguide.org/wiki/Ubuntu_Precise
Using NetBeans: Netbeans is a editor and compiler suite that allows to do development in
multiple languages. The latest version is 7.2
which can be downloaded here
http://netbeans.org/index.html
Download NetBeans for Linux 32 bit platform and when downloading select the All Bundle.
Installing NetBeans on Ubuntu: The downloaded file has a .sh extension for shell. In terminal
go to the folder where the installer is located using cd command. Then type the command chmod
+x <installer-file-name>.

13.

14.
15.
16.

17.
18.
19.
20.
21.
22.
23.

Double click the icon in explorer and install NetBeans. Installation help can be found here
http://netbeans.org/community/releases/72/install.html
Creating Java Application: Select File and then New Project and Select Java Application.
Create a Java Code that Displays your name. Show the output here.

Where is the output displayed? ___________________


What is the total build time? ___________
Performance Analysis: In this section the performance analysis of the standard insertion sort
algorithm will be judged on an Ubuntu and a Windows platform. The insertion sort Java
implementation
using
arrays
is
given
here
http://www.roseindia.net/java/beginners/arrayexamples/insertionsort.shtml
For the task we will select the array size to be 10, 15 and 20 so that the comparison is made on
same array sizes.
The syndicate will select an array for sorting and write it down.
Execute the algorithm on Ubuntu platform and record the Build Time. Additionally you may
record time of start of algorithm and time of exit algorithm and then displaying the difference as
the execution time.
Repeat steps 18 and 19 process on Windows with the same arrays.
Create a graph in LibreOffice calc.
Copy the graph and save it in Pinta (the MS Paint of Ubuntu). Save the image as JPEG. You will
need to download and install Pinta.
Copy the saved image here

12

CS 330 Operating Systems UBUNTU

(2)

(0.5)
(0.5)

(1)

24.

What is your conclusion from the graph?

(2)

25.

What did you learn in this experiment?

(2)

26.

Video Resources
http://www.youtube.com/watch?v=VuV8aR2D5Gs
Resources
https://help.ubuntu.com/
http://showmedo.com/videotutorials/ubuntu

27.

Summary:
In this experiment we have learned how to perform basic tasks in Ubuntu, change network
settings and how to create java codes in Ubuntu.

13

CS 330 Operating Systems UBUNTU

EXPERIMENT 3 CREATING PROCESS USING C++


1.
2.
3.

4.

5.

6.

Objectives:
(a). Creating processes in Ubuntu.
(b). Learning fork commands in Ubuntu
Time Required: 3 hrs
Software Required:
(a). Ubuntu/Linux and gcc compiler (already available in Ubuntu)
(b). Borland/Turbo C/Visual Studio for Windows Platform
(c). VMWare if required
(d). C language
How to compile C Program in Ubuntu/Linux
(a). Save your program with extension .c in any directory (working directory).
(b). Open Terminal.
(c). Navigate to the working directory
(d). Suppose you saved the program with name hello.c. Now write following lines:
gcc -c hello.c
gcc -o hello hello.c
./hello
(e). The first line compiles your program. Object file hello.o is created
(f). Second line makes an exe file with the name hello.
(g). Third line runs the exe file and shows output of the program.
Using getpid(): This function returns the pid of the current program. Use the following code and
write the output.
int main(){
int pid;
pid = getpid();
printf(Process ID is %d\n, pid);
return 0;
}

What is the outcome of the following program?


int main(){
long i;
printf(Process ID is %d\n, getpid());
for(i=0; i<=400;i++)
{
printf(i is %d\n, i);
}
return 0;
}

14

CS 330 Operating Systems Process

(1)

7.

Using getppid(): This function returns the pid of the parent process.
int main(){
int ppid;
ppid = getppid();
printf(Parent Process ID is %d\n, ppid);
return 0;
}
What is the outcome?

(1)

8.

Using fork(): fork command in Linux creates a new process by duplicating the calling process.
The new process, referred to as the child, is an exact duplicate of the calling process, referred to
as the parent.
(1)
http://manpages.ubuntu.com/manpages/lucid/man2/fork.2.html
What is the outcome of the following program?
int main(){
fork();
printf(The PID is %d\n, getpid());
return 0;
}

9.

What is the outcome of the following program?


int main(){
int pid;
pid = fork();
if(pid==0){
printf(I am the child, my process ID is %d\n, getpid());
printf(The childs parent process ID is %d\n, getppid());
}
else{
printf(I am the parent, my process ID is %d\n, getpid());
printf(The parent process ID is %d\n, getppid());
}
return 0;
}

15

CS 330 Operating Systems Process

(1)

10.

To see if the pid is same as shown in the system, Open System Monitor. Check to see if the pid is
same. Use the following code
int main(){
int pid,i;
pid = fork();
if(pid==0){
printf(I am the child, my process ID is %d\n, getpid());
printf(The childs parent process ID is %d\n, getppid());
}
else{
printf(I am the parent, my process ID is %d\n, getpid());
printf(The parent process ID is %d\n, getppid());
}
scanf(%d,&i); //so that program halts for user input
return 0;
}

11.

What do you understand from points 8, 9 and 10?

(3)

12.

Explain how was the execution carried out in program in point 11? You may use a flow model to
describe it.

(3)

13.

Reference Material/Web Resources


http://manpages.ubuntu.com/manpages/lucid/man2/fork.2.html
http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/exec.html
http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/forkexec.html
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch03-processes.pdf
Summary:
In this experiment we have learned how to create processes in Ubuntu and learnt to use fork commands.

16

CS 330 Operating Systems Process

EXPERIMENT 4 CREATING PROCESS IN UBUNTU AND WINDOWS


1.
2.
3.

4.

Objectives:
(a). Learning fork/exec commands in Ubuntu
(b). Creating process in Windows
Time Required: 3 hrs
Software Required:
(e). Ubuntu/Linux and gcc compiler (already available in Ubuntu)
(f). Borland/Turbo C/Visual Studio for Windows Platform
(g). VMWare if required
(h). C language
What is the outcome of this program?
/**
* This program forks a separate process using the fork()/exec() system calls.
* * Figure 3.10*
* @author Gagne, Galvin, Silberschatz Operating System Concepts - Seventh Edition
* Copyright John Wiley & Sons - 2005. */
#include <stdio.h>
#include <unistd.h>
3include<stdlib.h>
#include <sys/types.h>
int main(){
pid_t pid;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
perror(fork failed);//prints error message
exit(-1);
}
else if (pid == 0) { /* child process */
printf("I am the child %d\n",pid);
execlp("/bin/ls","ls",NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
printf("I am the parent %d\n",pid);
wait(NULL);
printf("Child Complete\n");
exit(0);
}
}

17

CS 330 Operating Systems Process

(1)

5.

Using Exec: The fork system call creates a new process but that process contains, and is
executing, exactly the same code that the parent process has. More often than not, we'd like to
run a new program.

6.

Example of Execve():The execve system call replaces the current process with a new
program.Type the following command in Terminal and show the output.
ls -aF /

Now execute the following code


/* execve: run a program */
#include <stdlib.h>
/* needed to define exit() */
#include <unistd.h>
/* needed to define getpid() */
#include <stdio.h> /* needed for printf() */
int main(int argc, char **argv) {
char *args[] = {"ls", "-aF", "/", 0}; /* each element represents a command line
argument */
char *env[] = { 0 };
/* leave the environment list null */
printf("About to run /bin/ls\n");
execve("/bin/ls", args, env);
perror("execve"); /* if we get here, execve failed */
exit(1);
}
What is the outcome?

7.

(1)

Using Execlp
execlp, which allows you to specify all the arguments as parameters to the function. Note that the
first parameter is the command. The second parameter is the first argument in the argument list
that is passed to the program (argv[0]). These are often the same but don't have to be. The last
parameter must be a null pointer.
/* execlp: run a program using execlp */
#include <stdlib.h>
/* needed to define exit() */
#include <unistd.h>
/* needed to define getpid() */
#include <stdio.h> /* needed for printf() */
int main(int argc, char **argv) {
printf("About to run ls\n");
execlp("ls", "ls", "-aF", "/", (char*)0);
perror("execlp"); /* if we get here, execlp failed */
exit(1);
}
What is the output?
(1)

18

CS 330 Operating Systems Process

8.

More help can be found here http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/exec.html

9.

Using fork() and exec(): The fork system call creates a new process. The execve system call
overwrites a process with a new program. A process forks itself and the child process execs a
new program, which overlays the one in the current process.
/* forkexec: create a new process. */
/* The child runs "ls -aF /". The parent wakes up after 5 seconds */
#include <stdlib.h>
/* needed to define exit() */
#include <unistd.h>
/* needed for fork() and getpid() */
#include <stdio.h> /* needed for printf() */
Int main(int argc, char **argv) {
void runit(void);
int pid; /* process ID */
switch (pid = fork()) {
case 0:
/* a fork returns 0 to the child */
runit();
break;
default: /* a fork returns a pid to the parent */
sleep(5); /* sleep for 5 seconds */
printf("I'm still here!\n");
break;
case -1: /* something went wrong */
perror("fork");
exit(1);
}
exit(0);
}
void runit(void) {
printf("About to run ls\n");
execlp("ls", "ls", "-aF", "/", (char*)0);
perror("execlp"); /* if we get here, execlp failed */
exit(1);
}
What is the outcome of the program?
(1)

10.

What do you understand from point 9?

19

CS 330 Operating Systems Process

(3)

11.

Creating a Process in Windows:


/**
* This program creates a separate process using the CreateProcess() system call. Figure 3.12
* @author Gagne, Galvin, Silberschatz Operating System Concepts - Seventh Edition
* Copyright John Wiley & Sons - 2005.
*/
#include <windows.h>
#include <stdio.h>
int main( VOID ){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) ); // Start the child process.
if( !CreateProcess( NULL, // No module name (use command line).
"C:\\WINDOWS\\system32\\mspaint.exe", // Command line.
NULL,
// Process handle not inheritable.
NULL,
// Thread handle not inheritable.
FALSE,
// Set handle inheritance to FALSE.
0,
// No creation flags.
NULL,
// Use parent's environment block.
NULL,
// Use parent's starting directory.
&si,
// Pointer to STARTUPINFO structure.
&pi )
// Pointer to PROCESS_INFORMATION structure.
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return -1;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}

12.

Which OS gives you a better interface for creating and executing child programs and why?

13.

Reference Material/Web Resources


http://manpages.ubuntu.com/manpages/lucid/man2/fork.2.html
http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/exec.html
http://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/forkexec.html
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch03-processes.pdf
Summary:
In this experiment we have learned how to execute fork commands in Ubuntu and how to create
processes in Windows.
20

CS 330 Operating Systems Process

(3)

EXPERIMENT 5 CREATING PROCESS USING JAVA


1.
2.
3.
4.
5.
6.
7.

8.

Objectives:
(a). Creating process in Java.
(b). Destroying processes in Java
Time Required: 3 hrs
Software Required:
(a). Windows OS
(b). NetBeans 7.2/JCreator
Process is a program in execution; process execution must progress in sequential fashion. A
process includes a program counter , stack and data section
Check the PID of WINWORD.EXE on your machine and write it here ___________
Close the WINWORD application, restart WINWORD after 1 minute and write the PID here
__________
What is your observation in points 5 and 6?

(2)

Getting PID of JVM through Java: For the given code show what is the output
import java.util.*;
import java.io.*;
import java.lang.management.*;
public class JavaPID {
public static void main(String args[]){
try{
System.out.println(ManagementFactory.getRuntimeMXBean().getName());
}
catch (Exception t){
t.printStackTrace();
}
}
}

9.

Describe what you understand from the output in point 8.

(2)

10.

In command prompt type mspaint and what is the output?

(1)

11.

Creating a Process in Java: A number of methods exist in Java to create a process. We will
follow the method through Java Process class. For the given code
import java.util.*;
import java.io.*;
import java.lang.management.*;

21

CS 330 Operating Systems Process

public class JavaExec {


public static void main(String args[]){
try {
System.out.println(ManagementFactory.getRuntimeMXBean().getName());
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("mspaint"); // execute mspaint
Thread.sleep(5000); // system sleeps for 5 seconds
proc.destroy(); // close mspaint
}
catch (Exception t){
t.printStackTrace();
}
}
}

12.

What is the output of point 11?

13.
14.

Now open Calculator and Freecell application using the same method
To get the exit value modify the code as follows

(2)

import java.util.*;
import java.io.*;
import java.lang.management.*;
public class JavaExec {
public static void main(String args[]){
try {
System.out.println(ManagementFactory.getRuntimeMXBean().getName());
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("mspaint"); // execute mspaint
Thread.sleep(5000); // system sleeps for 5 seconds
proc.destroy(); // close mspaint
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
}
catch (Exception t){
t.printStackTrace();
}
}
}

15.

What is the output of point 14?

16.

Re-execute point 14 but close the application in windows before the time expires. Write the
output here.

17.

What is your observation in Points 15 and 16?

(2)

18.

What did you learn in this experiment?

(1)

22

CS 330 Operating Systems Process

19.

Challenging Task: Make a program of CLI (Command Line Interface) which can understand
the command Open <App_Name> and Close_App_Name and open and close the mentioned
application.

20.

References
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Process.html
21. Video Resource:
http://www.youtube.com/watch?v=mwecn6UIzqc
www.cosmolearning.com/video-lectures/concurrency-processes-threads-and-address-spaces7406/
Summary:
In this experiment we have learned how to create and destroy processes in Java.

23

CS 330 Operating Systems Process

EXPERIMENT 6 PROCESS STATE MODEL


1.

Objectives:
(a). Learning process 5 State Process Model.
(b). Simulating 5 State Process Model.

2.

Time Required: 3 hrs

3.

Software Required:
(a). Java/C/C++/C#
(b). Windows/Ubuntu

4.

Process States: As a process executes, it changes state. The states of a process are: (a). New: The process is being created
(b). Running: Instructions are being executed
(c). Waiting: The process is waiting for some event to occur
(d). Ready: The process is waiting to be assigned to a process
(e). Terminated: The process has finished execution

5.

Process State Model: Process state models describe the life cycle of a process. The Process State
Model is given in Figure 1.

24

CS 330 Operating Systems Petersons Algorithm

Figure 1. Process State Model

6.

Simulate the 5-State Process Model that shows the execution of different processes. Assume the
following global parameters: (a). Ready Queue Size is 5
(b). Waiting Queue Size is 5
(c). The Switch from Ready Queue to Waiting Queue or vice versa takes a total of 2 Seconds.
(d). All Processes will be given a numerical PID for simulation.
(e). Simulate a Process Control Block that holds the total time required to execute and the time of
each I/O request.
(f). A timer counts the total execution seconds of a process and updates it in the PCB.
(g). You may use milliseconds or seconds as unit of time for your program simulation
(h). A Process automatically terminates after it is completed.

7.

The Program must show the following: (a). The Total Time Taken
(b). The current state of the Queues.
(c). The Creation and Termination times of Each Process.
25

CS 330 Operating Systems Petersons Algorithm

(6)

8.

For the information in following set create the trace and show the output.
(a). Example 1
PID

Creation
Time

Total CPU
Time

I/O Operations

P1

T1

10 Seconds

2 operations of 20 Seconds each

P2

T9

19 Seconds

1 of 10 Seconds, and 2 operations of 20 Seconds each

P3

T20

25 Seconds

2 operations of 40 seconds each

(b). Example 2

9.

PID

Creation
Time

Total CPU
Time

I/O Operations

P1

T1

20 Seconds

3 operations of 20 Seconds each

P2

T9

40 Seconds

1 of 5 Seconds, and 3 operations of 20 Seconds each

P3

T20

25 Seconds

2 operations of 40 seconds each

P4

T25

50 seconds

3 operations of 20 Seconds each

P5

T100

50 seconds

3 operations of 20 Seconds each

P6

T125

50 seconds

3 operations of 20 Seconds each

Applet at
26

CS 330 Operating Systems Petersons Algorithm

(4)

http://courses.cs.vt.edu/csonline/OS/Lessons/Processes/index.html
10.

More Resources
http://www.cs.kent.edu/~farrell/osf03/oldnotes/L06.pdf
http://www.slideserve.com/chas/process-description-and-control
http://www.youtube.com/watch?v=ZDQk6e3glfI

Summary:
In this experiment we have learned and simulated 5 state process model in multiple languages in different
operating systems.

27

CS 330 Operating Systems Petersons Algorithm

28

CS 330 Operating Systems Petersons Algorithm

EXPERIMENT 7 THREADS
1.

Objectives:
(a). Using Java Threads
(b). Thread Synchronization

2.

Time Required: 3 hrs

3.

Software Required:
(a). Java
(b). Windows/Ubuntu

4.

Multithreading: Multithreading refers to two or more tasks executing concurrently within a


single program. A thread is an independent path of execution within a program. Many threads can
run concurrently within a program.

5.

Context Switch Using Threads: Switching among threads is much cheaper than to switch
processes as threads share the same process area.

6.

Java Threads; Every thread in Java is created and controlled by the java.lang.Thread class. A
Java program can have many threads, and these threads can run concurrently, either
asynchronously or synchronously. Following shows the methods in Object and Thread Classes of
Java.

29

CS 330 Operating Systems Petersons Algorithm

7.

Thread Creation by Implementing The Runnable Interface:


public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then instantiate an
object of the class. We need to override the run() method into our class which is the only method
that needs to be implemented. The run() method contains the logic of the thread.
(a). A class implements the Runnable interface, providing the run() method that will be
executed by the thread. An object of this class is a Runnable object.
(b). An object of Thread class is created by passing a Runnable object as argument to the
Thread constructor. The Thread object now has a Runnable object that implements the
run() method.
(c). The start() method is invoked on the Thread object created in the previous step. The
start() method returns immediately after a thread has been spawned.
(d). The thread ends when the run() method ends, either by normal completion or by throwing
an uncaught exception.
Download and execute the code from here.
http://www.javabeginner.com/runnable-thread.zip
Post the output acquired on Ubuntu here: -

30

CS 330 Operating Systems Petersons Algorithm

(2)

8.

Thread Creation by Extending the Thread Class: The procedure for creating threads based on
extending the Thread is as follows:
(a). A class extending the Thread class overrides the run() method from the Thread class to
define the code executed by the thread.
(b). This subclass may call a Thread constructor explicitly in its constructors to initialize the
thread, using the super() call.
(c). The start() method inherited from the Thread class is invoked on the object of the class to
make the thread eligible for running.
Download and execute the code from here.
http://www.javabeginner.com/java-thread-example.zip
Post the output acquired on Ubuntu here: -

31

CS 330 Operating Systems Petersons Algorithm

(2)

9.

Tutorial can be found here: http://www.javabeginner.com/learn-java/java-threads-tutorial

10.

Create two threads one to read from a file and the other to write into another file. Show the
output trace for a given text file. Code can be found in this online book at page 136. Java
Programming by Example

(2)

11.

What is your learning in this experiment? Are threads better than processes? Why?

(4)

32

CS 330 Operating Systems Petersons Algorithm

12.

References
1. http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html [MUST VISIT]
2. http://www.javabeginner.com/learn-java/java-threads-tutorial

13.

Video Link
http://www.youtube.com/watch?v=KxTRsvgqoVQ
http://www.youtube.com/watch?v=D0u2USIonds
http://www.youtube.com/watch?v=CKFq-WTZZc8

Summary:
In this experiment we have learned how to use and synchronize threads in Java.

EXPERIMENT 8 PROCESS SCHEDULING


1.

Objectives:
(a). Learning process scheduling
(b). Comparing among FCFS and SJF scheduling algorithms through a simulation

2.

Time Required: 3 hrs


33

CS 330 Operating Systems Petersons Algorithm

3.

Software Required:
(a). Java/C/C++/C#
(b). Windows/Ubuntu

4.

Process Schedulers: Process schedulers are responsible for selecting which process to execute
so that overall performance is increased.

5.

Performance Metrics: Metrics include throughput, CPU overhead, response time, average wait
time etc.

6.

First Come First Served (FCFS) Scheduler: This scheduler implements a FIFO Queue and
schedules all process on their order of arrival.
http://cs.uttyler.edu/Faculty/Rainwater/COSC3355/Animations/fcfs.htm

7.

Shortest Job First (SJF) Scheduler: This scheduler priorities processes on the basis of their
CPU usage time.
http://sharingmythreeyears.blogspot.com/

8.

Comparison of Schedulers: Implement a queue of length 5 to hold processes for FCFS and SJF
both and for different algorithms observe the throughput at each second. To observe throughput
you have to mark at each instant how many processes have been executed for each scheduler.

9.

Assume that all processes arrive at initial time and burst time is available for each process.

10.

34

Process ID

Burst Time (Seconds)

P1

P2

P3

11

CS 330 Operating Systems Petersons Algorithm

11.

12.

13.

P4

P5

Process ID

Burst Time (Seconds)

P1

P2

10

P3

15

P4

20

P5

25

Process ID

Burst Time (Seconds)

P1

25

P2

20

P3

15

P4

10

P5

Given the states in Points 10, 11 and 12 schedule using both techniques and plot throughput on a
graph. The horizontal specifies the time and the vertical marks the total number of processes
completed so far.

35

CS 330 Operating Systems Petersons Algorithm

(5)

14.

Calculate average wait time for each algorithm and for all three states on Points 10, 11 and 12.
Average wait time is the sum of waiting times by each process divided by the total number of
processes

(2)

15.

What is your conclusion based on the throughput and average wait time as well as the type of
input.

(3)

36

CS 330 Operating Systems Petersons Algorithm

16.

Resources
http://www.cosmolearning.com/video-lectures/concurrency-processes-threads-and-addressspaces-7406/

17.

Video Links
http://www.youtube.com/watch?v=FiGKndlvO8I
http://www.youtube.com/watch?v=u9VOokHuXIA
http://www.youtube.com/watch?v=bta48Ix3t_Q

37

CS 330 Operating Systems Petersons Algorithm

Summary:
In this experiment we have learned process scheduling and simulated scheduling algorithms and then compared
them based on their throughput and wait time.

EXPERIMENT 9 PETERSONS ALGORITHM


1.

Objectives:
(a). Critical Section
(b). Petersons Algorithm

2.

Time Required: 3 hrs

3.

Software Required:
(a). Java/C/C++/C#
(b). Windows/Ubuntu

4.

Create two processes (producer and consumer) or functions that access the same shared variable.
38

CS 330 Operating Systems Petersons Algorithm

One process increments the variable while the other decrements it. The maximum value of the
variable is 5 and the producer cannot produce anymore items if the variable is 5. The consumer
cannot consume if the variable is zero.
5.

In the main function write a sequence of calls that simulate the producer consumer problem.
Output the normal case, the case where the consumer should be blocked and the case where the
producer should be blocked. Show the trace only.

(2)

6.

How does race condition occur in the cases of point 5? Explain and trace the case.

(2)

39

CS 330 Operating Systems Petersons Algorithm

7.

Critical Section: Access to a shared item is considered critical and is carried out in critical
section only.

8.

Petersons Solution: It provides a solution to the Critical Section.


Two processes share two variables:
int turn;
boolean flag[2];
//The variable turn indicates whose turn it is to enter the critical section

40

CS 330 Operating Systems Petersons Algorithm

//The flag array is used to indicate if a process is ready to enter the critical section. //flag[i] =
true implies that process Pi is ready!
9.

Algorithm for Process Pi:


do {
flag[i] = True;
turn = j;
while (flag[j] && turn = j){
//busy waiting
}
//go to critical section i.e., access the shared item
flag[i] = FALSE;
// go to remainder section
} while (TRUE);

10.

Implement and show trace of Petersons Algorithm for two processes. Show output here.

41

CS 330 Operating Systems Petersons Algorithm

(3)

11.

Implement and show trace of Petersons Algorithm for three processes. Show output here.

12.

References

(3)

http://en.wikipedia.org/wiki/Peterson%27s_algorithm
http://www.techopedia.com/definition/27325/petersons-algorithm

Summary:
In this experiment we have implemented Petersons algorithm for two and three processes and evaluated their
output through trace graphs

42

CS 330 Operating Systems Petersons Algorithm

EXPERIMENT 10 SEMAPHORES
1.

Objectives:
(a). Solving critical section problem using semaphores.
(b). Semaphore implementation.

2.

Time Required: 3 hrs

3.

Software Required:
(a). Java/C/C++/C#
(b). Windows/Ubuntu

4.

Semaphores: An integer value used for signalling among processes. Only three operations may be
performed on a semaphore, all of which are atomic:
Initialize,
Decrement (Wait)
Increment. (Signal)

signal (S) {
S++;
}
5.

When one process modifies semaphore value, no other process can simultaneously modify that
semaphore. When a process releases resource, it performs signal. When count goes to 0, all
resources are being used. After that, process that wish to use a resource will block until count
becomes greater than 0.

6.

Counting Semaphore: Integer value can range over an unrestricted domain. Counting semaphores
can be used to control access to a given resource with finite number of instances.
43

CS 330 Operating Systems Semaphores

7.

Binary Semaphore: Integer value can range only between 0 and 1. They are simpler to implement.
Binary semaphores can be used to deal with critical section problem.
Semaphore mutex;

// initialized to 1

do {
wait (mutex);
// Critical Section
signal (mutex);
// remainder section
} while (TRUE);
8.

9.

Create a semaphore class that implements a semaphore for mutual exclusion. Also implement a
producer class and a consumer class that acquire the use of a shared resource through the shared
semaphore. Both the producer and consumer should implement the wait and signal method.

10.

Show the trace of a simulation highlighting the following cases: 44

CS 330 Operating Systems Semaphores

(8)

(a). Normal execution.


(b). Producer is blocked.
(c). Consumer is blocked.

11.

What is your understanding of synchronization through semaphores based on this experiment?

45

CS 330 Operating Systems Semaphores

(2)

12.

References
http://en.wikipedia.org/wiki/Semaphore_(programming)
http://elvis.rowan.edu/~hartley/ConcProgJava/Semaphores/bbou.java
http://www.cs.loyola.edu/~jglenn/702/F2007/Examples/Producer_Consumer_Semaphores/pc_sema
phore.html

13.

Video Link

46

CS 330 Operating Systems Semaphores

http://freevideolectures.com/Course/2260/Computer-Science-III-Programming-Paradigms/16

Summary:
In this experiment we have implemented semaphores for scheduling processes in operating system.

47

CS 330 Operating Systems Semaphores

EXPERIMENT 11 LINUX MODULES


1.
2.
3.
4.

5.

Objectives:
(a). Module programming
(b). Developing Modules In Linux
Time Required: 3 hrs
Software Required: C on Ubuntu
Modules: In computing, a loadable kernel module (or LKM) is an object file that contains code
to extend the running kernel, or so-called base kernel, of an operating system. LKMs are
typically used to add support for new hardware, file-systems, or for adding system calls. When
the functionality provided by an LKM is no longer required, it can be unloaded in order to free
memory and other resources.
Creating Hello World Module: In this experiment the simplest hello world module will be
created. The steps are as follows: (a). Make a folder on the desktop for this lab. Make sure that the name of the folder does not
have a space character in it. Write the name of the folder here ______________.
(b). Create a text file using a text editor with the name hello-1.c. You may create any file
name but the extension should be .c.
(c). Write the following code in the text file

(1)

#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
int init_module(void){
printk(KERN_INFO "Sky Fall\n");
// A non 0 return means init_module failed
// module can't be loaded.
return 0;
}
void cleanup_module(void){
printk(KERN_INFO "Breaking Dawn.\n");
}

(d).
(e).

6.

Do not compile the code as yet.


Kernel modules must have at least two functions: a "start" (initialization) function called
init_module() which is called when the module is loaded (insmod) into the kernel, and an
"end" (cleanup) function called cleanup_module() which is called just before it is
removed (rmmod).
(f). printk() is not meant to communicate information to the user. It happens to be a logging
mechanism for the kernel, and is used to log information or give warnings. To view the
log system log has to be seen. Open terminal and navigate to the working directory and
type lsmod to list the modules loaded in the kernel.
Compiling Hello World Module: Now the module will be compiled by creating a make file.
The steps are as under: (a). Create a new file using the text editor and store it with the name Makefile in the working
directory. Do not use any extensions while storing the file. Type the following commands
in the Makefile
obj-m += hello-1.o
all:

make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules

clean:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean

48

CS 330 Operating Systems -.Linux Modules

(3)

(b).
(c).
(d).
(e).

The first line should show the name of your file with .o extension after the += characters.
Do not forget to put a tab character before make in both instances of the keyword make.
In the terminal type sudo make. If asked for the password type in the password.
What is the outcome of this step (if correctly executed)? Show the output as well as the
names of the files created in the working directory.

(f). Use modinfo hello-1.ko to see what kind of information it is. Show the output here.

7.
8.

Loading Module: To load the module in kernel type sudo insmod ./hello-1.ko and remember to
rename hello-1 if you have different file name.
Type lsmod and see if the module is loaded. Show the screen capture here.

(1)

9.

Viewing Log: To view log type dmesg. Show the output here.

(1)

10.
11.
12.

Removing Modules: To remove module type sudo rmmod hello-1 and remember to rename
hello-1 if you have different file name.
Type lsmod and see if the module is unloaded.
Type dmesg again and show the output here.

(1)

13.
14.

Helping link: http://www.tldp.org/LDP/lkmpg/2.6/html/x181.html


Hello World Improved: Write the following code in a new file. Name the file hello-2.c
#include <linux/module.h>
/* Needed by all modules */
#include <linux/kernel.h>
/* Needed for KERN_INFO */
#include <linux/init.h>
/* Needed for the macros */
static int __init hello_2_init(void){
printk(KERN_INFO "Hello, world 2\n");
return 0;
}
static void __exit hello_2_exit(void){
printk(KERN_INFO "Goodbye, world 2\n");
}
module_init(hello_2_init);
module_exit(hello_2_exit);

49

CS 330 Operating Systems -.Linux Modules

15.

Remember that there are two underscores before init and exit keywords
Modify the make file as follows:
obj-m += hello-1.o
obj-m += hello-2.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:

16.
17.
18.

make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean

19.

Type sudo make to compile new module


Check the module directory by typing lsmod
Insert modules by typing sudo insmod ./hello-1.ko and sudo insmod ./hello-2.ko and remember
to rename filenames if you have different file name
Check the log by typing dmesg. Show the output here.

(1)

10.
11.

Remove the modules by typing sudo rmmod hello-1 and then sudo rmmod hello-2
Show the output of dmesg

(1)

12.

What did you learn in this experiment?

(1)

13.

Resources
https://en.wikipedia.org/wiki/Loadable_kernel_module
Videos
http://www.youtube.com/watch?v=8JBZc5OasFg
http://www.youtube.com/watch?v=o768iZKtzBA

14.

Summary:
In this experiment we have learned how to develop and removes modules in Linux .

50

CS 330 Operating Systems -.Linux Modules

EXPERIMENT 12 IPC
1.

Objectives:
1. To write a program for inter-process communication using shared memory.
2. To write a program for inter-process communication using pipe processing.

2.

Time Required: 3 hrs

3.

Software Required:
(c). Java/C/C++/C#
(d). Windows/Ubuntu

4.

Shared Memory: A shared memory is an extra piece of memory that is attached to some address
spaces for their owners to use. As a result, all of these processes share the same memory segment
and have access to it. Consequently, race conditions may occur if memory accesses are not
handled properly. The following figure shows two processes and their address spaces. The yellow
rectangle is a shared memory attached to both address spaces and both process 1 and process 2
can have access to this shared memory as if the shared memory is part of its own address space.
In some sense, the original address space is "extended" by attaching this shared memory.

5.

Algorithm to implement the program for inter-process communication


(a). Start the program
(b). Create the child process using fork()
(c). Create the shared memory for parent process using shmget() system call
(d). Now allow the parent process to write inn shared memory using shmpet pointer which is
(e). return type of shmat()
(f). Now across and attach the same shared memory to the child process
51

CS 330 Operating Systems -.IPC

(g). The data in the shared memory is read by the child process using the shnot pointer
(h). Now, detach and rebase the shared memory
(i). Stop the program
6.

Pipe Processing: 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.

7.

Let us now describe how we may accomplish this.


(a).

First we have a parent process which declares a pipe in it.

(b). Next we spawn two child processes. Both of these would get the pipe definition which we
have defined in the parent. The child processes, as well as the parent, have both the write
and read ends of the pipe open at this time.
(c). Next, one child process, say Process A, closes its read end and the other child process,
Process B, closes its write end.
(d). The parent process closes both write and read ends.
(e). Next, Process A is populated with code to get a string and Process B is populated to
52

CS 330 Operating Systems -.IPC

reverse a string. With the above arrangement the output from Process A is piped as input
to Process B.
The programs given below precisely achieve this.
In reading the programs, the following interpretations have to be borne in mind:
(a).

The pipe is defined by the declaration pipe(p_des).

(b). The dup command replaces the standard I/O channels by pipe descriptors.
(c). The execlp command is used to populate the child process with the desired code.
(d). The close command closes the appropriate ends of the pipe.
(e). The get_str and rev_str processes are pre-compiled to yield the required executables.
8.

Algorithm to implement the program for inter-process communication using Pipe


Processing
Algorithm:
(a).

Start the program.

(b).

Create the child process using fork().

(c).

Create the pipe structure using pipe().

(d).

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

(e).

Write the data in the pipe using write().

(f).

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

(g).

Read the data in the pipe using read().

53

CS 330 Operating Systems -.IPC

(h).

Display the string.

(i).

Stop the program.

9.

Using the algorithm above, write a program to implement inter-process communication

10.

References
http://www.sriengg.com/wp-content/uploads/2012/05/CS2257-OS-LAB-MANUAL-II-IT-byGBN.pdf
Video Links

http://en.wikipedia.org/wiki/Inter-process_communication
http://www.youtube.com/watch?v=5T4xZ9f7Bfc
http://www.youtube.com/watch?v=ukGjIgVsZjI

Summary:
In this experiment we have learned how to implement inter-process communication programs in
shared memory and pipe memory.
54

CS 330 Operating Systems -.IPC

(10)

55

CS 330 Operating Systems -.IPC

EXPERIMENT 13 MLFQ
1.

Objectives: To learn the advanced process scheduling algorithms with priorities and multi-level
feedback queues.

2.

Time Required: 3 hrs

3.

Software Required:
(e). Java/C/C++/C#
(f). Windows/Ubuntu

4.

Priority Scheduling
Sometimes, processes are not equally important. For instance, we may want to see long CPUintensive (non-interactive) processes get a lower priority than interactive processes. These
processes, in turn, should get a lower priority than jobs that are critical to the operating system.
In addition, different users may have different status. A system administrator's processes may
rank above those of a student's. These goals led to the introduction of priority scheduling.
The idea here is that each process is assigned a priority (just a number). Of all processes ready to
run, the one with the highest priority gets to run next. With a priority scheduler, the scheduler
simply picks the highest priority process to run. If the system uses preemptive scheduling, a
process is preempted whenever a higher priority process is available in the ready list.
Dynamic Priority: A process with a dynamic priority will have that priority changed by the
scheduler during its course of execution. For example, the scheduler may decide to decrease a
process' priority to allow a lower-priority job to run.
Advantage: Priority scheduling provides a good mechanism where the relative importance of
each process may be precisely defined.
Disadvantage and its remedy: If high priority processes use up a lot of CPU time, lower priority
processes may starve and be postponed indefinitely. The situation where a process never gets
scheduled to run is called starvation. One approach to the problem of indefinite postponement is
to use dynamic priorities. At the expiration of each quantum, the scheduler can decrease the
priority of the current running process (thereby penalizing it for taking that much CPU time).
Eventually its priority will fall below that of the next highest process and that process will be
allowed to run.
56

CS 330 Operating Systems -.MLFQ

Multi-level Queues:
Processes can be grouped into priority classes and assigned a separate run queue for each class;
for instance, separate queues for system processes, interactive processes, low-priority interactive
processes, and background non-interactive processes. The scheduler picks the highest-priority
queue (class) that has at least one process in it. In this sense, it behaves like a priority scheduler.
It then picks a process from the queue. Each queue may use a different scheduling algorithm,
(e.g., typically round robin with a different quantum). For example, low-priority non-interactive
processes could be given a longer quantum. They won't get to run as often since they are in a low
priority queue but, when they do, the scheduler will let them run longer.

Multi-level queues are generally used as a top-level scheduling discipline to separate broad
classes of processes, such as real-time, kernel threads, interactive, and background processes.
Specific schedulers within each class determine which process gets to run within that class.
5.

Multilevel feedback queues


A variation on multilevel queues is to allow the scheduler to adjust the priority of a process: to
relocate it from one queue to another based on the behaviour of the process. The goal of
multilevel feedback queues is to automatically place processes into priority levels based on their
CPU burst behaviour. I/O-intensive processes will end up on higher priority queues and CPUintensive processes will end up on low priority queues.
The key to the algorithm is that high priority queues have short time slices. The quantum length
increases with each decreasing priority queue. A process initially starts in the highest priority
queue. Once it gets scheduled to run, it will either run or then block on some event or it will run
until the quantum expires. If the process blocks then the scheduler will move the process onto the
same priority queue when it is ready to run again. If, however, the process runs to expiration (i.e.,
the scheduler sees that the process is still running when its quantum expires) then the scheduler
pre-empts the process and places it in the queue at the next lower priority level.

57

CS 330 Operating Systems -.MLFQ

As long as a process uses the full quantum at each level, it continues to drop to lower priority
levels (eventually reaching the lowest level, where it circulates round robin). At each lower
priority level, the quantum is increased (so the process does not get the CPU often, but gets to
use more of it when it does get it). The rationale for this is that processes at lower levels have
demonstrated that they are compute bound rather than I/O bound. By giving them a fatter chunk
of the CPU, but only when there are no higher priority processes to run, we can minimize the
context switch overhead and get more efficient use of the CPU.
A process that waits too long to be scheduled may be moved up to a higher-priority queue
(process aging). While it's common for each queue to circulate processes round-robin, as with
multilevel queues, each queue may have its own scheduling algorithm to determine the order in
which the scheduler removes a process from the queue.

Multi-level feedback queues work well in favouring I/O bound processes with frequent
scheduling by keeping them at high priorities.
Advantages: Multi-level feedback queues are good for separating processes into categories based
on their need for a CPU. They favour I/O bound processes by letting them run often. Versions of
this scheduling policy that increases the quantum at lower priority levels also favor CPU bound
processes by giving them a larger chunk of CPU time when they are allowed to run.
Disadvantages: The priority scheme here is one that is controlled by the system rather than by
the administrator or users. A process is deemed important not because it is, but because it
happens to do a lot of I/O. This scheduler also has the drawback that I/O bound processes that
become CPU bound or CPU bound processes that become I/O bound will not get scheduled well.
6.

Performance Metrics:
Different performance metrics are used to measure the efficiency of scheduling algorithms. They
are briefly described below.

58

CS 330 Operating Systems -.MLFQ

(a). Throughput: The total number of processes that complete their execution per time unit.
(b). Turnaround time: Total time between submission of a process and its completion.
(c). Response time: Amount of time it takes from when a request was submitted until the first
response is produced.
(d). Waiting Time: Equal CPU time to each process (or more generally appropriate times
according to each process' priority). It is the time for which the process remains in the ready
queue.
7.

For the following processes with arrival time and burst time given.
Process ID

Burst Time (Seconds)

Arrival

P1

25

P2

20

P3

15

P4

10

P5

10

Implement the Multi-level Feedback Queue.


(a). Q1 is running RR algorithm with Q=4s,
(b). Q2 is running RR algorithm with Q=8 and
(c). Q3 is running FCFS algorithm.
For the process information in Exercise 1, implement the multi-level feedback queue with time
slices (time shared among various queues) for different queues.
59

CS 330 Operating Systems -.MLFQ

(10)

(a). Q1 has highest priority with 55% of CPU time,


(b). Q2 has second higest with 30% of CPU time;
(c). Q3 has least priority with 15% of CPU time.
Find the Average Waiting Time and throughput for Exercise 1 and Exercise 2.

8.

References
1. http://www.cs.rutgers.edu/~pxk/416/notes/07-scheduling.html
2. http://sharingmythreeyears.blogspot.com/

9.

Video
60

CS 330 Operating Systems -.MLFQ

http://www.youtube.com/watch?v=6vk2yMwa2n0
http://www.youtube.com/watch?v=XONQb3dj78g

Summary:
In this experiment we have learned advanced scheduling algorithms with priority queues and multilevel
feedback, and used performance metrics to calculate the efficiency of algorithms.

61

CS 330 Operating Systems -.MLFQ

EXPERIMENT 14 MEMORY MANAGEMENT


1.

Objectives: To write a program for first fit and best fit algorithm for memory management.

2.

Time Required: 3 hrs

3.

Software Required:
(c). Java
(d). Windows/Ubuntu

4.

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 descriptor 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 called fragmentation, and is a problem for all memory-management strategies, although it is
particularly bad for best-fit. One way to avoid making little holes is to give the client a bigger
block than it asked for. For example, we might round all requests up to the next larger multiple of
64 bytes. That doesn't make the fragmentation go away, it just hides it. Unusable space in the
form of holes is called external fragmentation

62

CS 330 Operating Systems -.Memory Management

5.

Algorithm
Start the program.
(a). Get the number of segments and size.
(b). Get the memory requirement and select the option.
(c). If the option is 2 call first fit function.
(d). If the option is 1 call best fit function.
(e). Otherwise exit.
(f). For first fit, allocate the process to first possible segment which is free.
(g). 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.
(h). Stop the program.
Implement the algorithm

6.

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
63

CS 330 Operating Systems -.Memory Management

(5)

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.
7.

Algorithm
(a). Start the program
(b). Obtain the number of sequences, number of frames and sequence string from the user
(c). 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
(d). In LRU algorithm, when a page fault occurs, the page which most recently used is
removed
(e). Display the number of faults
(f). Stop the program
Implement the code

64

CS 330 Operating Systems -.Memory Management

(5)

8.

Resources
https://en.wikipedia.org/wiki/Memory_management

9.

Video
http://www.youtube.com/watch?v=PSPF_ELJ0cY

Summary:
In this experiment we have written codes and implemented best fit and first fit algorithms used in
65

CS 330 Operating Systems -.Memory Management

memory management.

66

CS 330 Operating Systems -.Memory Management

I hear and I forget,


I see and I remember,
I do and I understand

Confucius

67

CS 330 Operating Systems -.Memory Management

68

CS 330 Operating Systems -.Memory Management

S-ar putea să vă placă și