Sei sulla pagina 1di 48

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

1 CS 330 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.

2 CS 330 Operating Systems


VERSION HISTORY
Date Version Updated By Details
September 2012 1.0 LE Umar Mahmud First Version Created
August 2014 1.1 Lec Mobeena Shahzad Updated Experiment 4 and Experiment 5
August 2015 1.2 Lec Mobeena Shahzad CLOs defined with each experiment
September 2016 1.3 Lec Mobeena Shahzad/ LE Reviewed and updated all the experiments
Aamna Mehfooz
October 2017 1.4 Lec Mobeena Shahzad /LE Reviewed and updated all the experiments
Aamna Mehfooz
September 2019 1.5 Lec Mobeena Shahzad/ LE
Aamna Mehfooz

3 CS 330 Operating Systems


Dept of CSE
Lab Rubrics
(Programming Related Subjects)
Group 1
Criteria Unacceptable Substandard Adequate Proficient
(Marks=0) Marks=1 Marks=2 Marks=3
R1 The program failed The program execution let The program The program was
Completeness to produce the right to inaccurate or incomplete was correctly correctly functional, and
and Accuracy accurate result results. It was not correctly functional and all the features were
functional or not all the most of the implemented
features were implemented features were
implemented
R2 Coding standards, Coding standards, best Coding Coding standards, best
Coding best programming programming practices are standards, programming practices
Standards practices are not not followed best are followed
followed. Student programming appropriately.
cannot understand practices are
the code rarely
followed
R3 Student failed to Student has basic Student has Student has
Demonstration demonstrate a clear knowledge of understanding basic demonstrated on
understanding of but asked questions were knowledge of accurate understanding
the assigned task not answered. understanding of the lab objective and
. Answer to concepts. All the
the question questions are answered
are basic completely and correctly
R4 The code is huge The code is brute force and The code is The code is extremely
Efficiency and appears to be unnecessarily long fairly efficient efficient without
patched together. without sacrificing readability and
sacrificing understanding.
readability
and
understanding
.
R5 The code is not Some parts of the code Most of the The code could be reused
Reusability organized for could be reused in other code could be as a whole, or each
reusability. programs reused in routine could be reused.
other
programs.
R6 Most part of the Working program is Working Working program has
Originality working program is uninspired and program has potential for making a
copied. straightforward work with some creative contribution.
little to no creative potential for
potential. making a
creative
contribution

4 CS 330 Operating Systems


CS-330 Operating System
Course Learning Outcomes (CLOs)
At the end of the course the students will be able to: PLOs BT Level*
1. Explain and summarize OS services and Abstractions 1 C-2
2. Analyse the applicability of different OS Algorithms 2 C-4
3. Apply the knowledge of OS services to implement algorithms 3 C-3
4. Produce programs to use and implement OS services 5 P-4

Mapping of CLOs to Lab Experiments

List of Experiments CLO RG


1 Introduction to Operating Systems 1 1
2 Ubuntu 1 1
3 Process State Model 4 1
4 Creating process using C++ part 1 4 1
5 Creating Process using C++ part 2 4 1
6 Creating Process using Java 4 1
7 Threads 4 1
8 Process Scheduling 4 1
9 MLFQ 4 1
10 Semaphores part 1 4 1
11 Semaphores part 2 4 1
12 Dynamic Memory Allocation 4 1
13 Page Replacement Algorithms 4 1
14 Linux Modules 4 1
15 Semester Project 4 1,3

5 CS 330 Operating Systems


Max. Marks Obtained Instructor
Date Experiment
Marks R1 R2 R3 R4 R5 R6 Sign

Grand Total

6 CS 330 Operating Systems


List of Experiment
EXPERIMENT 1 – INTRODUCTION TO OPERATING SYSTEMS .................................................................................................. 8
EXPERIMENT 2 – UBUNTU .................................................................................................................................................... 13
EXPERIMENT 3 – PROCESS STATE MODEL ............................................................................................................................ 17
EXPERIMENT 4 – CREATING PROCESS USING C++ ................................................................................................................ 19
EXPERIMENT 5 – CREATING PROCESS USING C++ ................................................................................................................ 22
EXPERIMENT 6 – CREATING PROCESS USING JAVA .............................................................................................................. 25
EXPERIMENT 7 – THREADS.................................................................................................................................................... 28
EXPERIMENT 8 – PROCESS SCHEDULING .............................................................................................................................. 31
EXPERIMENT 9 – MLFQ ......................................................................................................................................................... 33
EXPERIMENT 10 – SEMAPHORES .......................................................................................................................................... 37
EXPERIMENT 11 – SEMAPHORES .......................................................................................................................................... 39
EXPERIMENT 12 – DYNAMIC MEMORY ALLOCATION ........................................................................................................... 41
EXPERIMENT 13 – PAGE REPLACEMENT ALGORITHMS ........................................................................................................ 43
EXPERIMENT 14 – LINUX MODULES ..................................................................................................................................... 45

7 CS 330 Operating Systems


EXPERIMENT 1 – INTRODUCTION TO OPERATING SYSTEMS ( CLO-1 )
1. Objectives:
(a). Practical usage of different OS.
(b). Working with common system tools in Windows and Ubuntu
2. Time Required: 3 hrs
3. Software Required:
(a). MS DOS
(b). Windows OS
(c). Ubuntu OS

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

Operating System

Introduction
A computer system can be divided into 4 components:

- Hardware (CPU, memory, input/output devices, etc.),


- Operating system,
- System programs (word processors, spread sheets, accounting software’s, compilers,)
- Application programs.

In 1960’s definition of an operating system is “software that controls the hardware”.


However, today, due to microcode we need a better definition. We see an operating system as the
programs that make the hardware useable. In brief, an operating system is the set of programs that
controls a computer.

An Operating system is software that creates a relation between the User, Software and
Hardware. It is an interface between the all. All the computers need basic software known as an
Operating System (OS) to function.

The OS acts as an interface between the User, Application Programs, Hardware and the System
Peripherals. The OS is the first software to be loaded when a computers starts up. The entire
application programs are loaded after the OS.

Types of Operating System (Based of No. of user):

1. Single User: If the single user Operating System is loaded in computer’s memory; the computer
would be able to handle one user at a time.
Ex: MS-Dos, MS-Win 95-98, Win-ME

1. Multi user: If the multi-user Operating System is loaded in computer’s memory; the computer
would be able to handle more than one user at a time.
Ex: UNIX, Linux, XENIX

2. Network: If the network Operating System is loaded in computer’s memory; the computer would

8 CS 330 Operating Systems


be able to handle more than one computer at time.
Ex: Novel Netware, Win-NT, Win-2000-2003

Operating Systems Types

Single- And Multi-Tasking Operating Systems


A single-tasking system can only run one program at a time, while a multi-tasking
operating system allows more than one program to be running in concurrency. This is achieved by
time-sharing, dividing the available processor time between multiple processes that are each
interrupted repeatedly in time slices by a task-scheduling subsystem of the operating system.
Multi-tasking may be characterized in preemptive and co-operative types. In preemptive
multitasking, the operating system slices the CPU time and dedicates a slot to each of the
programs. Unix-like operating systems, e.g., Solaris, Linux, as well as AmigaOS support
preemptive multitasking.

Single- And Multi-User Operating Systems


Single-user operating systems have no facilities to distinguish users, but may allow
multiple programs to run in tandem. A multi-user operating system extends the basic concept of
multi-tasking with facilities that identify processes and resources, such as disk space, belonging to
multiple users, and the system permits multiple users to interact with the system at the same time.
Time-sharing operating systems schedule tasks for efficient use of the system and may also
include accounting software for cost allocation of processor time, mass storage, printing, and
other resources to multiple users.

Distributed Operating Systems


A distributed operating system manages a group of distinct computers and makes them
appear to be a single computer. The development of networked computers that could be linked
and communicate with each other gave rise to distributed computing. Distributed computations
are carried out on more than one machine. When computers in a group work in cooperation, they
form a distributed system.

Embedded Operating Systems


Embedded operating systems are designed to be used in embedded computer systems.
They are designed to operate on small machines like PDAs with less autonomy. They are able to
operate with a limited number of resources. They are very compact and extremely efficient by
design. Windows CE and “Minix 3”are some examples of embedded operating systems.

5. Components of the OS are shown as below

9 CS 330 Operating Systems


Disk Operating System (DOS)
6. 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.
7. Press Windows key + r and type cmd. What was the outcome?

8. Type HELP to view a list of commands.


9. Use the TIME command to set the new time.
10. Set the title to your name using the TITLE command
11. Is DOS Case-Sensitive? (True/False)
12. Do DOS allow two tasks to be done simultaneously? Give comments?

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

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

14. Windows

Windows is a graphical, multi-tasking OS developed by Microsoft since 1985.


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

10 CS 330 Operating Systems


16. Processes: A Process is a program in execution. A program is a combination of code and data.
17. Terminate the process WINWORD.EXE. What was the effect?

18. In the Performance Tab, What are the current CPU usage, the Paged pool?
What is your computer’s RAM type?

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

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

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

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

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

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

25. What did you learn in this experiment?

26. What is an operating system?

11 CS 330 Operating Systems


What are the components present in computer?
27. 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-an-
introduction-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
o Further Guide can be found here http://ubuntuguide.org/wiki/Ubuntu_Precise

28. Video Resources


http://www.youtube.com/watch?v=VuV8aR2D5Gs
http://www.youtube.com/watch?v=1FJHYqE0RDg
http://www.youtube.com/watch?v=MaA0vFKt-ew
29. Summary:
In this experiment we have learned how to use different operating systems (Windows, Ubuntu)
and how to use their tools.

12 CS 330 Operating Systems


EXPERIMENT 2 – UBUNTU ( CLO-1 )
1. Objectives:
(a). Using Ubuntu and beginner’s 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.
2. Time Required: 3 hrs
3. Software Required:
(a). Ubuntu OS/Windows OS
(b). NetBeans 7.2
4. Some of the Linux directories that may interest you include the following:

 /bin - Contains common Linux user commands, such as ls, sort , date etc.
 /boot - Has the bootable Linux kernel and boot loader configuration files (GRUB).
 /dev - Contains files representing access points to devices on your systems. These include
terminal devices ( tty* ), floppy disks ( fd* ), hard disks ( hd* or sc* ), RAM ( ram* ), and CD-
ROM ( cd* ). (Applications normally access these devices directly through the device files,
but end users rarely access them directly.)
 /etc - Contains administrative configuration files.
 /home - Contains directories assigned to each user with a login account.
 /media - Provides a location for mounting devices, such as remote file systems and
removable media (with directory names of cdrom , floppy , and so on). In Fedora and RHEL,
many removable media are mounted automatically in this directory when the media is
inserted (CD or DVD) or connected (USB pen drives or cameras ).
 /proc - Provides a mechanism for the kernel to send information to processes.
 /root - Represents the root user's home directory.
 /sbin - Contains administrative commands and daemon processes.
 /sys - A /proc -like file system, added with the Linux 2.6 kernel and intended to contain files
for getting hardware status and reflecting the system's device tree as it is seen by the
kernel. It pulls many of its functions from /proc .
 /tmp - Contains temporary files used by applications.
 /usr - Contains user documentation, games , graphical files (X11), libraries (lib), and a variety
of other user and administrative commands and files.
o /var - Contains directories of data used by various applications. In particular, this is
where you would place files that you share as an FTP server ( /var/ftp ) or a Web
server ( /var/www ). It also contains all system log files ( /var/log ). In time, FTP,
HTTP, and similar services will move to the /srv directory to adhere to the Linux
Standards Base ( www.freestandards.org/spec ).
5. 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

13 CS 330 Operating Systems – UBUNTU


(b). File and Directory Commands
(6) The tilde (~) symbol stands for your home directory. If you are user, then the tilde
(~) stands for /home/user
(7) pwd: The pwd command will allow you to know in which directory you're
located (pwd stands for "print working directory").
(8) 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.
(9) cd: The cd command will allow you to change directories.
(10) 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".
(11) mv: The mv command will move a file to a different location or will rename a
file.
(12) rm: Use this command to remove or delete a file in your directory.
(13) rmdir: The rmdir command will delete an empty directory.
(14) mkdir: The mkdir command will allow you to create directories.

(c). System Information Commands


(15) df: The df command displays file system disk space usage for all mounted
partitions.
(16) 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:
(17) ip addr reports on your system's network interfaces.

6.

14 CS 330 Operating Systems – UBUNTU


The commands can be combined using the pipeline (| ) operator. For example, number of users
logged in can be obtained as.
who | wc –l

Finally to terminate the unix session execute the command exit or logout.

15 CS 330 Operating Systems – UBUNTU


7. What is the difference between df df –h and df –l commands?
8. Type ifconfig in terminal. What does ifconfig show?

9. Create a graph in LibreOffice calc.


10. 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.
11. Copy the saved image here

12. What is your conclusion from the graph?

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


14. System Monitor: This tool is the equivalent of task manager in windows. Identify what all
information is displayed in System Monitor.

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

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

17. What did you learn in this experiement?


18. Video Resources
http://www.youtube.com/watch?v=VuV8aR2D5Gs
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

19. Resources
https://help.ubuntu.com/
http://showmedo.com/videotutorials/ubuntu
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.

16 CS 330 Operating Systems – UBUNTU


EXPERIMENT 3 – PROCESS STATE MODEL ( CLO-4 )
1. Objectives:
(a). Learning 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.

Figure 1. Process State Model


(a). ` `
6.
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.

8. For the information in following set create the trace and show the output.

(a). Example 1

PID Creation Total CPU I/O Operations


Time Time
P1 T1 10 Seconds 2 operations of 20 Seconds each

17 CS 330 Operating Systems – Process


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

PID Creation Total CPU I/O Operations


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

9. Applet at 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 using examples.

18 CS 330 Operating Systems – Process


EXPERIMENT 4 – CREATING PROCESS USING C++ ( CLO-4 )
1. Objectives:
(a). Creating processes in Ubuntu
(b). Learning fork/exec commands in Ubuntu

2. Time Required: 3 hrs


3. Software Required:
(a). Ubuntu/Linux and gcc compiler (already available in Ubuntu)
(b). VMWare if required
(c). C /C++ language
4. 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 //compiles; object file hello.o is created
gcc -o hello hello.c //makes an exe file with the name hello
./hello //runs the exe file and shows the output

5. 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;
}

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

7. Using fork():

19 CS 330 Operating Systems – Process


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

8. What is the outcome of the following program?


To see if the pid is same as shown in the system, open System Monitor. Check to
see if the pid is same.
int main(){
int pid;
pid = fork();
if (pid==0){
printf (“I am the child, my process ID is %d\n”, getpid());
printf (“The child’s 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;
}

9. What do you understand from points 7 and 8?

13. Reference Material/Web Resources

20 CS 330 Operating Systems – Process


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

21 CS 330 Operating Systems – Process


EXPERIMENT 5 – CREATING PROCESS USING C++ ( CLO-4 )
1. Objectives:
(c). Creating processes in Windows
(d). Learning exec/ execlp commands in Ubuntu

2. Time Required: 3 hrs


3. Software Required:
(d). Ubuntu/Linux
(e). VMWare if required
(f). C /C++ language
4. 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.
There is no exec system call -- this is usually used to refer to all the execXX calls as
a group. They all do essentially the same thing: loading a new program into the
current process, and provide it with arguments and environment variables. The
differences are in how the program is found, how the arguments are specified, and
where the environment comes from.

 The calls with v in the name take an array parameter to specify the argv[]
array of the new program.

 The calls with l in the name take the arguments of the new program as a
variable-length argument list to the function itself.

 The calls with e in the name take an extra argument to provide the
environment of the new program; otherwise, the program inherits the
current process's environment.

 The calls with p in the name search the PATH environment variable to find
the program if it doesn't have a directory in it (i.e. it doesn't contain a /
character). Otherwise, the program name is always treated as a path to the
executable.
5.
Using Execlp: execlp 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.
More help can be found here http://www.cs.rutgers.edu/~pxk/416/notes/c-
tutorials/exec.html
6.
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

22 CS 330 Operating Systems – Process


* Copyright John Wiley & Sons - 2005. */

#include <stdio.h>
#include <unistd.h>
#include<stdlib.h>
#include <sys/types.h>
int main(){
pid_t pid;
pid = fork(); // fork a child process
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
printf ("I am the parent %d\n",pid);
wait (NULL); // parent will wait for the child to
complete

printf ("Child Complete\n");


exit (0);
}
}

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

23 CS 330 Operating Systems – Process


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 );
}
8. 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 Windows and
learned exec and execlp commands.

24 CS 330 Operating Systems – Process


EXPERIMENT 6 – CREATING PROCESS USING JAVA ( CLO-4 )
1. Objectives:
(a). Creating process in Java.
(b). Destroying processes in Java
2. Time Required: 3 hrs
3. Software Required:
(a). Windows OS
(b). NetBeans 7.2/JCreator
4. 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();
}
}
}

5. Describe what you understand from the output in point 4.

6. 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 write the
output.
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
}
catch (Exception t){
t.printStackTrace();
}
}

25 CS 330 Operating Systems – Process


}

7 Write a Program to open an application (firefox) as a separate process. After it is


opened, the program should wait for 10 seconds and then destroy the process
8 Create a process using Process class and open up a notepad application, then destroy
the process instantly to get an exit value.
9. Now open Calculator using the same method

10. To get the exit value modify the code as follows. What is the output?
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();
}
}
}

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

12. What did you learn in this experiment?

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

26 CS 330 Operating Systems – Process


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

27 CS 330 Operating Systems – Process


EXPERIMENT 7 – THREADS ( CLO-4 )
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.

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:
28 CS 330 Operating Systems – Process
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: -

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


tutorial
10. Create a simple thread.
11. 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

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

13. References
1. http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html [MUST
VISIT]

29 CS 330 Operating Systems – Process


2. http://www.javabeginner.com/learn-java/java-threads-tutorial

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

30 CS 330 Operating Systems – Process


EXPERIMENT 8 – PROCESS SCHEDULING ( CLO-4 )
1. Objectives:
(a). Learning process scheduling
(b). Comparing among FCFS and SJF scheduling algorithms through a simulation
2. Time Required: 3 hrs
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. Process ID Burst Time (Seconds)
P1 5
P2 8
P3 11
P4 4
P5 2
11. Process ID Burst Time (Seconds)
P1 5
P2 10
P3 15
P4 20
P5 25

12. Process ID Burst Time (Seconds)


P1 25
P2 20
P3 15
P4 10
P5 5

31 CS 330 Operating Systems – Process


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

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

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

16. Resources
http://www.cosmolearning.com/video-lectures/concurrency-processes-threads-and-
address-spaces-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

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

32 CS 330 Operating Systems – Process


EXPERIMENT 9 – MLFQ ( CLO-4 )
1. Objectives: To learn the advanced process scheduling algorithms with priorities and
multi-level feedback queues.

2. Time Required: 3 hrs


3. Software Required:
(a). Java/C/C++/C#
(b). Windows/Ubuntu
4. Priority Scheduling
Sometimes, processes are not equally important. For instance, we may want to see
long CPU-intensive (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.
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.

33 CS 330 Operating Systems – Process


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

34 CS 330 Operating Systems – Process


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.
(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.
ProcessID Burst Time (Seconds) Arrival
P1 25 0
P2 20 3
P3 15 5
P4 10 8
P5 5 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

35 CS 330 Operating Systems – Process


with time slices (time shared among various queues) for different queues.
(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
http://www.youtube.com/watch?v=6vk2yMwa2n0
http://www.youtube.com/watch?v=XONQb3dj78g

36 CS 330 Operating Systems – Process


EXPERIMENT 10 – SEMAPHORES ( CLO-4 )
1. Objectives:
(a). Solving critical section problem using semaphores.
(b). Semaphore implementation.
2. Time Required: 3 hrs
3. Software Required:
(c). Java/C/C++/C#
(d). 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:
(a). Initialize,
(b). Decrement (Wait)
(c). Increment. wait (S){ signal (S)
(Signal) while (S <= 0) {
{ S++;
; // wait }
}
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.
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.
Sem’aphore mutex; // initialized to 1
do {
wait (mutex);
// Critical Section
signal (mutex);
// remainder section
} while (TRUE);

37 CS 330 Operating Systems – Process


8.

9.
Create a program which can create any number of threads user inputs. Create a
semaphore that implements a semaphore for mutual exclusion. Also implement
threads that acquire the use of a shared resource through the shared semaphore in
similar critical section. Threads should implement the wait and signal method having
similar handler. Show the output. (10 marks)

10. 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_Semap
hores/pc_semaphore.html
http://www.amparo.net/ce155/sem-ex.html
11. Video Link
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

38 CS 330 Operating Systems – Process


EXPERIMENT 11 – SEMAPHORES ( CLO-4 )
1. Objectives:
(c). Solving critical section problem using semaphores.
(d). Semaphore implementation.
2. Time Required: 3 hrs
3. Software Required:
(e). Java/C/C++/C#
(f). 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:
(d). Initialize,
(e). Decrement (Wait)
(f). Increment. wait (S){ signal (S)
(Signal) while (S <= 0) {
{ S++;
; // wait }
}
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.
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.acquire();
semaphore.release();
8.

Create a program which can create any number of threads user inputs. Create a
semaphore that implements a semaphore for mutual exclusion. Also implement
threads that acquire the use of a shared resource through the shared semaphore in
similar critical section. Threads should implement the wait and signal method having
similar handler(acquire/release). Show the output. (10 marks)

9. 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_Semap
hores/pc_semaphore.html
http://www.amparo.net/ce155/sem-ex.html
39 CS 330 Operating Systems – Process
10. Video Link
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

40 CS 330 Operating Systems – Process


EXPERIMENT 12 – DYNAMIC MEMORY ALLOCATION ( CLO-4 )
1. Objectives: To write a program for first fit and best fit algorithm for memory
2. management
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
5. memory.

First Fit
First Fit 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,
6. 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

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

41 CS 330 Operating Systems – Process


b. Allocate the process to the segment which is equal to or slightly
greater than the process size.
(h). Stop the program.
8. Implement the algorithm

9. Resources: https://en.wikipedia.org/wiki/Memory_management
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 memory management.

42 CS 330 Operating Systems – Process


EXPERIMENT 13 – PAGE REPLACEMENT ALGORITHMS ( CLO-4 )
1. Objectives: To write a program for FIFO and LRU algorithms for memory management
2. Time Required: 3 hrs
3. Software Required:
a) Java
b) Windows/Ubuntu

4. First-In First-Out (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.
5.
Least Recently Used (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.
6.
Algorithm
(a). Start the program
(b). Define 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 is least recently used is
removed
(e). Display the number of faults
(f). Stop the program
Implement the code

7. Resources
https://en.wikipedia.org/wiki/Memory_management
Video
http://www.youtube.com/watch?v=PSPF_ELJ0cY

Summary:

43 CS 330 Operating Systems – Process


In this experiment we have written codes and implemented FIFO and LRU algorithms used
in memory management.

44 CS 330 Operating Systems – Process


EXPERIMENT 14 – LINUX MODULES ( CLO-4 )
1. Objectives:
(a). Module programming
(b). Developing Modules In Linux
2. Time Required: 3 hrs
3. Software Required: C on Ubuntu
4. 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.
5. Creating Hello World Module: In this experiment the simplest hello world (1)
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
#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). Do not compile the code as yet.


(e). 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.
6. Compiling Hello World Module: Now the module will be compiled by creating a (3)
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
45 CS 330 Operating Systems – Process
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean
(b). The first line should show the name of your file with .o extension after the
+= characters.
(c). Do not forget to put a tab character before make in both instances of the
keyword make.
(d). In the terminal type sudo make. If asked for the password type in the
password.
(e). 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. 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.
8. 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. Removing Modules: To remove module type sudo rmmod hello-1 and remember
to rename hello-1 if you have different file name.
11. Type lsmod and see if the module is unloaded.
12. Type dmesg again and show the output here. (1)

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

46 CS 330 Operating Systems – Process


14. 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);
Remember that there are two underscores before init and exit keywords
15. 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:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean

16. Type sudo make to compile new module


17. Check the module directory by typing lsmod
18. 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
19. Check the log by typing dmesg. Show the output here. (1)

10. Remove the modules by typing sudo rmmod hello-1 and then sudo rmmod hello-
2
11. Show the output of dmesg (1)

12. What did you learn in this experiment? (1)

47 CS 330 Operating Systems – Process


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

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

48 CS 330 Operating Systems – Process

Potrebbero piacerti anche