You are on page 1of 59

Department of Computer Science and Engineering

Operating System Lab


[BTCS 404-18]

B.Tech 2nd Year- 4th Semester

Submitted To: Submitted By:


Dr. Parveen Priyanshu Pandey
Assistant Professor 2101777
CSE 4th Sem

Chandigarh Engineering College


Landran (Mohali)
1
Page

Priyanshu Pandey 2101777 OS


Table of Content
1. Installation of various Operating System ............................................................................... 1
1a. Steps to install windows operating system in a computer................................................ 1
1b. Steps to install Linux Operating System. ......................................................................... 8
2. Implementation of CPU scheduling algorithms to find turnaround time and waiting time. 14
2a. FCFS .............................................................................................................................. 14
2b. SJF.................................................................................................................................. 17
2c. Round Robin (pre-emptive) ........................................................................................... 21
2d. Priority ........................................................................................................................... 25
3. Virtualization, Installation of Virtual Machine Software and installation of Operating
System on Virtual Machine ..................................................................................................... 28
4. Commands for files & directories: cd, ls, cp, md, rm, mkdir, rmdir. Creating and viewing
files using cat. File comparisons. Disk related commands: checking disk free spaces.
Processes in linux, connecting processes with pipes, background processing, managing
multiple processes. Manual help. Background process: changing process priority, scheduling
of processes at command, batch commands, kill, ps, who, sleep. Printing commands, grep,
fgrep, find, sort, cal, banner, touch, file. File related commands ws, sat, cut, grep. ................ 36
5. Shell Programming: Basic of shell programming, various types of shell, Shell
programming in bash, conditional & looping statement, case statements, parameter passing
and arguments, shell variables, shell keywords, creating shell programs for automate system
tasks, report printing. ............................................................................................................... 46
SHELL PROGRAMS .............................................................................................................. 50
5a. To create a script to enter a string and then print its manipulation table. ...................... 50
5b. To create a script to accept a number and compute it's factorial. .................................. 51
5c. Write a script to determine whether a given number is prime or not. ............................ 52
5d. Write a shell script to find out whether the number entered is odd or even. ................. 53
5e. To Create a shell script ‘add phone’ that asks a user for a name and then a phone
Number. ............................................................................................................................... 54
6. Implementation of Bankers algorithm for the purpose of deadlock avoidance ................... 55
2
Page

Priyanshu Pandey 2101777 OS


1. Installation of various Operating System

1a. Steps to install windows operating system in a computer.


● Steps to Install:
1. First get your ISO disk image file from Microsoft.com and buy a CD key.

2. Now get an USB flash drive or optical CD Drive and create a bootable device drive
from Power ISO/Rufus. Here I’m using a USB flash Drive.

3. Once Completed reboot your PC and press ESC/DEL/F10 to enter into the BIOS.
Check the key online according to your PC brand. In BIOS edit boot sequence
program and set your bootable device on top. Now Save and Exit BIOS. If done
correctly your PC will start booting from your bootable device.
1
Page

Priyanshu Pandey 2101777 OS


4. Once booted successfully you’ll see the first window of installation. Now here
Choose your Language, Time and currency format, Keyboard layout or let it be the
Default i.e. English (US) and hit Next.

5. Now you will see a Install Now button hit it to start the setup.

6. Once you hit Install Now the setup will start gathering hardware information and it
will automatically take you to the next level.

2
Page

Priyanshu Pandey 2101777 OS


7. Now on next window it will ask you for your CD key. Enter the CD key you have
bought from the Microsoft. You can use the on-screen keyboard or normal keyboard.

8. Select the Version of Windows you want to install.

9. Now accept the Terms and Conditions from Microsoft and hit Next.

3
Page

Priyanshu Pandey 2101777 OS


10. Now choose an option suitable for you. You can upgrade a previously installed
window or custom install from the scratch. Here I’m selecting Custom installation.

11. Now after you select Custom installation you will land on a window called as
Partitioning window. Here you can create different Local Disk partitions of your HDD
drive or you can select the partition containing the previous window.

12. Once you are done with your partitioning hit Next and your window will start
installing. After it finishes up the window will ask for reboot. Reboot the window and
remove your bootable device before window boot again. 4
Page

Priyanshu Pandey 2101777 OS


13. Once Setup is done you need to net up window environment as per your requriment.

5
Page

Priyanshu Pandey 2101777 OS


14. After setting the environment you need to Sign up/Log in to your account to use the
Windows.

6
Page

Priyanshu Pandey 2101777 OS


15. After your settings you will be asked to Name your PC and User and set a password.

16. After Setting the Pin your device is ready to use after displaying the screen message.

7
Page

Priyanshu Pandey 2101777 OS


1b. Steps to install Linux Operating System.

Introduction: Ubuntu is an operating system with Linux kernel based on Debian and
distributed as free and open source software. It’s one of the most popular operating systems
for Desktop and Server.

Ubuntu can be installed in two ways as follows:

1. Using a DVD?

It’s easy to install Ubuntu from a DVD. Here’s what you need to do:

Put the Ubuntu DVD into the DVD-drive

Restart your computer. You should see a welcome screen prompting you to choose your
language and giving you the option to install Ubuntu or try it from the DVD.

If you don’t get this menu, read the booting from the DVD guide for more information.

2. Using a USB drive

The steps to install Ubuntu using USB are as follows:

Step 1: Most new computers can boot from USB. You should see a welcome screen
prompting you to choose your language and giving you the option to install Ubuntu or try it
from the CD.

If your computer doesn’t automatically do so, you might need to press the F12 key to bring
up the boot menu, but be careful not to hold it down – that can cause an error message.

Step 2: Prepare to install Ubuntu

• We recommend you plug your computer into a power source


8


Page

You should also make sure you have enough space on your computer to install
Ubuntu

Priyanshu Pandey 2101777 OS


• We advise you to select Download updates while installing and Install this third-party
software now
• You should also stay connected to the internet so you can get the latest updates while
you install Ubuntu
• If you’re not connected to the internet, we’ll help you set up wireless at the next step

Step 3: Set up wireless

If you are not connected to the internet, you will be asked to select a wireless network, if
available. We advise you to connect during the installation so we can ensure your machine is
up to date. So, if you set up your wireless network at this point, it’s worth then clicking the
Back button to go back to the last screen (Preparing to install Ubuntu) and ticking the box
marked ’Download updates while installing’.

9
Page

Priyanshu Pandey 2101777 OS


Step 4: Allocate drive space

Use the checkboxes to choose whether you’d like to Install Ubuntu alongside another
operating system, delete your existing operating system and replace it with Ubuntu, or — if
you’re an advanced user — choose the ’Something else’ option

Step 5: Begin the installation

Depending on your previous selections, you can now verify that you have chosen the way in
which you would like to install Ubuntu. The installation process will begin when you click
the Install Now button.

Ubuntu needs about 4.5 GB to install, so add a few extra GB to allow for your files.

10
Page

Priyanshu Pandey 2101777 OS


Step 6 : Select your location

If you are connected to the internet, this should be done automatically. Check your location is
correct and click ’Forward’ to proceed. If you’re unsure of your time zone, type the name of
the town you’re in or click on the map and we’ll help you find it.

Step 7: Select your preferred keyboard layout

Click on the language option you need. If you’re not sure, click the ’Detect Keyboard
Layout’ button for help.

11
Page

Priyanshu Pandey 2101777 OS


Step 8: Enter your login and password details

Step 9: Learn more about Ubuntu while the system installs…

12
Page

Priyanshu Pandey 2101777 OS


Step 10: That’s it.

All that’s left is to restart your computer and start enjoying Ubuntu!

Step 11: Ubuntu is ready to use

13
Page

Priyanshu Pandey 2101777 OS


2. Implementation of CPU scheduling algorithms to find turnaround time and waiting
time

2a. FCFS
First Come First Serve Scheduling:

ALGORITHM:

1. Start the program.


2. Get the number of processes and their burst time.
3. Initialize the waiting time for process 1 and 0.
4. Process for(i=2;i<=n;i++),wt.p[i]=p[i-1]+bt.p[i-1].
5. The waiting time of all the processes is summed then average value time is
calculated.
6. The waiting time of each process and average times are displayed
7. Stop the program

PROGRAM
#include<iostream>
using namespace std;

void findWaitingTime(int processes[], int n,


int bt[], int wt[])
{
wt[0] = 0;

for (int i = 1; i < n ; i++ )


wt[i] = bt[i-1] + wt[i-1] ;
}

void findTurnAroundTime( int processes[], int n,


int bt[], int wt[], int tat[])
{
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}
14
Page

Priyanshu Pandey 2101777 OS


void findavgTime( int processes[], int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

findWaitingTime(processes, n, bt, wt);

findTurnAroundTime(processes, n, bt, wt, tat);

cout << "Processes "<< " Burst time "<< " Waiting time " << " Turn around time\n";

for (int i=0; i<n; i++)


{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "<< (float)total_wt / (float)n;


cout << "\nAverage turn around time = "<< (float)total_tat / (float)n;
}

int main()
{
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

int burst_time[] = {10, 5, 8};


findavgTime(processes, n, burst_time);
return 0;
}
15
Page

Priyanshu Pandey 2101777 OS


OUTPUT:

16
Page

Priyanshu Pandey 2101777 OS


2b. SJF
SHORTEST JOB FIRST SCHEDULING

ALGORITHM:
1. Start the program. Get the number of processes and their burst time.
2. Initialize the waiting time for process 1 as 0.
3. The processes are stored according to their burst time.
4. The waiting time for the processes are calculated a follows:
for(i=2;i<=n;i++).wt.p[i]=p[i=1]+bt.p[i-1].
5. The waiting time of all the processes summed and then the average time is calculate
6. The waiting time of each processes and average time are displayed.
7. Stop the program.
PROGRAM:
#include <bits/stdc++.h>
using namespace std;

struct Process {
int pid;
int bt;
int art;
};

void findWaitingTime(Process proc[], int n,


int wt[])
{
int rt[n];

for (int i = 0; i < n; i++)


rt[i] = proc[i].bt;

int complete = 0, t = 0, minm = INT_MAX;


17

int shortest = 0, finish_time;


Page

Priyanshu Pandey 2101777 OS


bool check = false;

while (complete != n) {

for (int j = 0; j < n; j++) {


if ((proc[j].art <= t) &&
(rt[j] < minm) && rt[j] > 0) {
minm = rt[j];
shortest = j;
check = true;
}
}

if (check == false) {
t++;
continue;
}

rt[shortest]--;

minm = rt[shortest];
if (minm == 0)
minm = INT_MAX;

if (rt[shortest] == 0) {

complete++;
check = false;

finish_time = t + 1;
18
Page

wt[shortest] = finish_time -

Priyanshu Pandey 2101777 OS


proc[shortest].bt -
proc[shortest].art;

if (wt[shortest] < 0)
wt[shortest] = 0;
}
t++;
}
}

void findTurnAroundTime(Process proc[], int n,


int wt[], int tat[])
{
for (int i = 0; i < n; i++)
tat[i] = proc[i].bt + wt[i];
}

void findavgTime(Process proc[], int n)


{
int wt[n], tat[n], total_wt = 0,
total_tat = 0;

findWaitingTime(proc, n, wt);
findTurnAroundTime(proc, n, wt, tat);

cout << "Processes "


<< " Burst time "
<< " Waiting time "
<< " Turn around time\n";
19

for (int i = 0; i < n; i++) {


Page

total_wt = total_wt + wt[i];

Priyanshu Pandey 2101777 OS


total_tat = total_tat + tat[i];
cout << " " << proc[i].pid << "\t\t"
<< proc[i].bt << "\t\t " << wt[i]
<< "\t\t " << tat[i] << endl;
}

cout << "\nAverage waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}
int main()
{
Process proc[] = { { 1, 6, 1 }, { 2, 8, 1 },
{ 3, 7, 2 }, { 4, 3, 3 } };
int n = sizeof(proc) / sizeof(proc[0]);
findavgTime(proc, n);
return 0;
}
OUTPUT:

20
Page

Priyanshu Pandey 2101777 OS


2c. Round Robin (pre-emptive)
ROUND ROBIN SCHEDULING

ALGORITHM:
1. Get the number of process and their burst time.
2. Initialize the array for Round Robin circular queue as ‘0’.
3. The burst time of each process is divided and the quotients are stored on the round
Robin array.
4. According to the array value the waiting time for each process and the average time
are calculated as line the other scheduling.
5. The waiting time for each process and average times are displayed.
6. Stop the program.
PROGRAM:
#include<iostream>
using namespace std;

void findWaitingTime(int processes[], int n,


int bt[], int wt[], int quantum)
{
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

int t = 0;

while (1)
{
bool done = true;

for (int i = 0 ; i < n; i++)


{
21

if (rem_bt[i] > 0)
Page

Priyanshu Pandey 2101777 OS


done = false;

if (rem_bt[i] > quantum)


{
t += quantum;
rem_bt[i] -= quantum;
}
else
{
t = t + rem_bt[i];
wt[i] = t - bt[i];
rem_bt[i] = 0;
}
}
}
if (done == true)
break;
}
}

void findTurnAroundTime(int processes[], int n,


int bt[], int wt[], int tat[])
{
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

void findavgTime(int processes[], int n, int bt[],


int quantum)
{
22

int wt[n], tat[n], total_wt = 0, total_tat = 0;


Page

Priyanshu Pandey 2101777 OS


findWaitingTime(processes, n, bt, wt, quantum);

findTurnAroundTime(processes, n, bt, wt, tat);

cout << "Processes "<< " Burst time "<< " Waiting time " << " Turn around time\n";

for (int i=0; i<n; i++)


{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

int main()
{
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

int burst_time[] = {10, 5, 8};

int quantum = 2;
findavgTime(processes, n, burst_time, quantum);
return 0;
23

}
Page

Priyanshu Pandey 2101777 OS


OUTPUT:

24
Page

Priyanshu Pandey 2101777 OS


2d. Priority
PRIORITY SCHEDULING
ALGORITHM:
1. Start the program.
2. Read burst time, waiting time, turn the around time and priority.
3. Initialize the waiting time for process 1 and 0.
4. Based up on the priority process are arranged
5. The waiting time of all the processes is summed and then the average waiting time
6. The waiting time of each process and average waiting time are displayed based on the
priority.
7. Stop the program.

PROGRAM:
#include<bits/stdc++.h>
using namespace std;

struct Process
{
int pid;
int bt;
int priority;
};

bool comparison(Process a, Process b)


{
return (a.priority > b.priority);
}

void findWaitingTime(Process proc[], int n,


int wt[])
25

{
Page

Priyanshu Pandey 2101777 OS


wt[0] = 0;

for (int i = 1; i < n ; i++ )


wt[i] = proc[i-1].bt + wt[i-1] ;
}
void findTurnAroundTime( Process proc[], int n,
int wt[], int tat[])
{
for (int i = 0; i < n ; i++)
tat[i] = proc[i].bt + wt[i];
}
void findavgTime(Process proc[], int n)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;
findWaitingTime(proc, n, wt);
findTurnAroundTime(proc, n, wt, tat);
cout << "\nProcesses "<< " Burst time "
<< " Waiting time " << " Turn around time\n";
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << proc[i].pid << "\t\t"
<< proc[i].bt << "\t " << wt[i]
<< "\t\t " << tat[i] <<endl;
}

cout << "\nAverage waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
26

<< (float)total_tat / (float)n;


Page

Priyanshu Pandey 2101777 OS


void priorityScheduling(Process proc[], int n)
{
sort(proc, proc + n, comparison);
cout<< "Order in which processes gets executed \n";
for (int i = 0 ; i < n; i++)
cout << proc[i].pid <<" " ;
findavgTime(proc, n);
}
int main()
{
Process proc[] = {{1, 10, 2}, {2, 5, 0}, {3, 8, 1}};
int n = sizeof proc / sizeof proc[0];
priorityScheduling(proc, n);
return 0;
}

OUTPUT:

27
Page

Priyanshu Pandey 2101777 OS


3. Virtualization, Installation of Virtual Machine Software and installation of Operating
System on Virtual Machine

Introduction
Virtual Box allows you to run an entire operating system inside another operating system.
Please be aware that you should have a minimum of 512 MB of RAM. 1 GB of RAM or
more is recommended.

Comparison to Dual-Boot
Many websites (including the one you're reading) have tutorials on setting up dual-boots
between Windows and Ubuntu. A dual-boot allows you, at boot time, to decide which
operating system you want to use. Installing Ubuntu on a virtual machine inside of Windows
has a lot advantages over a dual-boot (but also a few disadvantages).

Advantages of virtual installation

• The size of the installation doesn't have to be predetermined. It can be a dynamically


resized virtual hard drive.
• You do not need to reboot in order to switch between Ubuntu and Windows.
• The virtual machine will use your Windows internet connection, so you don't have to
worry about Ubuntu not detecting your wireless card, if you have one.
• The virtual machine will set up its own video configuration, so you don't have to
worry about installing proprietary graphics drivers to get a reasonable screen
resolution.
• You always have Windows to fall back on in case there are any problems. All you
have to do is press the right Control key instead of rebooting your entire computer.
• For troubleshooting purposes, you can easily take screenshots of any part of Ubuntu
(including the boot menu or the login screen).
• It's low commitment. If you later decide you don't like Ubuntu, all you have to do is
delete the virtual hard drive and uninstall VirtualBox.

Disadvantages of virtual installation

• In order to get any kind of decent performance, you need at least 512 MB of RAM,
because you are running an entire operating system (Ubuntu) inside another entire
operating system (Windows). The more memory, the better. I would recommend at
least 1 GB of RAM.
• Even though the low commitment factor can seem like an advantage at first, if you
later decide you want to switch to Ubuntu and ditch Windows completely, you cannot
simply delete your Windows partition. You would have to find some way to migrate
out your settings from the virtual machine and then install Ubuntu over Windows
outside the virtual machine.
• Every time you want to use Ubuntu, you have to wait for two boot times (the time it
takes to boot Windows, and then the time it takes to boot Ubuntu within Windows).

Installation Process
Step 1: The first thing you have to do is to install oracle VirtualBox. Install it the same way
28

you would any normal Windows program. Then get Ubuntu disk image (.iso file).
Page

Priyanshu Pandey 2101777 OS


Step 2: After you launch VirtualBox from the Windows Start menu, click on New to create a
new virtual machine. When the New Virtual Machine Wizard appears, click Next.

Step 3: You can call the machine whatever you want. If you're installing Ubuntu, it makes
sense to call it Ubuntu, I guess. You should also specify that the operating system is Linux.

Step 4: VirtualBox will try to guess how much of your memory (or RAM) to allocate for the
29

virtual machine. If you have 1 GB or less of RAM, I would advise you stick with the
recommendation. If, however, you have over 1 GB, about a quarter your RAM or less should
Page

be fine. For example, if you have 2 GB of RAM, 512 MB is fine to allocate. If you have 4

Priyanshu Pandey 2101777 OS


GB of RAM, 1 GB is fine to allocate. If you have no idea what RAM is or how much of it
you have, just go with the default.

Click Next.

Step 5: If this is your first time using VirtualBox (which it probably is if you need a tutorial
on how to use it), then you do want to Create new hard disk and then click Next.

30

Step 6: Click Next again.


Page

Priyanshu Pandey 2101777 OS


Step 7: Theoretically, a dynamically expanding virtual hard drive is best, because it'll take up
only what you actually use. I have come upon weird situations, though, when installing new
software in a virtualized Ubuntu, in which the virtual hard drive just fills up instead of
expanding. So I would actually recommend picking a Dynamically allocated.

31
Page

Priyanshu Pandey 2101777 OS


Step 8: Ubuntu's default installation is less than 3 GB. If you plan on adding software or
downloading large files in your virtualized Ubuntu, you should tack on some buffer.

Step 9: Click Create and wait for the virtual hard drive to be created. This is actually just a
very large file that lives inside of your Windows installation.

32
Page

Priyanshu Pandey 2101777 OS


Step 10: The next thing to do to make the (currently blank) virtual hard drive useful is to add
the downloaded Ubuntu disk image (the .iso) boot on your virtual machine. Click on Settings
and Storage. Then, under CD/DVD Device, next to Empty, you'll see a little folder icon.
Click that.

Step 11:Select the Ubuntu .iso you downloaded earlier.

Step 12: Once you've selected it, click OK.


33

Then double-click your virtual machine to start it up.


Page

Priyanshu Pandey 2101777 OS


Step 13: You may get a bunch of random warnings/instructions about how to operate the
guest operating system within VirtualBox. Read those, and then you may also want to mark
not to see those again.

Step 14: Wait for Ubuntu to boot up.

34
Page

Priyanshu Pandey 2101777 OS


Step 15: Once it's started up, just follow the regular installation procedure as if you were
installing.

35
Page

Priyanshu Pandey 2101777 OS


4. Commands for files & directories: cd, ls, cp, md, rm, mkdir, rmdir. Creating and
viewing files using cat. File comparisons. Disk related commands: checking disk free
spaces. Processes in linux, connecting processes with pipes, background processing,
managing multiple processes. Manual help. Background process: changing process
priority, scheduling of processes at command, batch commands, kill, ps, who, sleep.
Printing commands, grep, fgrep, find, sort, cal, banner, touch, file. File related
commands ws, sat, cut, grep.

CLASSIFICATION OF COMMANDS

1. User Access and User ID commands


2. Directory Commands
3. Editor Commands
4. File Manipulation commands
5. Security and Protection.
6. Inter-user and inter-machine communication commands
7. Information commands
8. Process Management commands
9. Program Development and Debugging commands
10. Text Processing commands
11. I/O Redirection and Piping
12. Shell commands and shell programming
13. Invoking command interpreters
14. System Administration commands for
a. Normal day-to-day administration
b. System monitoring
c. Installation and operation
d. Accounting

USER ACCESS AND USER ID COMMANDS


✓ Login :
This command means to log in to the system. It is a process by which user
identifies himself to the system. The system prompts with a message : Login :
✓ Logging off :
The new login message indicates that the session has been terminated thus
making it available for the next user. The exit command or ctrl+d means to logout the
system.
✓ Password :
Set the user's password or change the earlier login password. Password is a
sequence of letters and digits i.e. used to verify that user is allowed to use this user id.
Syntax :- password:

DIRECTORY COMMANDS
1. To create a Directory: This command is used for creating a Directory.
36

Syntax: cat >Directory name


Page

Priyanshu Pandey 2101777 OS


2. To Open a Directory: This command is used for Opening a Directory.
Syntax: cd Directoryname

3. To Create a File: This command is used for creating a file.


Syntax: cat >file name

4. To List all files: This command is used list all the files running in putty.
Syntax: ls

5. To Append a file:This command is used to add information to the created file.


Syntax: cat >> file name

6. To remove a Directory:This command is used to remove a Directory.


Syntax: rmdir directory name

FILE MANIPULATION COMMANDS


37

1) cat:
The cat command allows us to create single or multiple files.
Page

Syntax: cat > Filename

Priyanshu Pandey 2101777 OS


Ctrl+D command is used to exit the file.

The cat command is also used to display content of a file on the screen.
Syntax: cat Filename

Sometimes you will need to append text to an already existing text file. This text
could come from any source, such as a line of text from the command line, the output
of a command or from another text file.This can also be achieved using cat command.
Syntax: cat >> Filename

2) cp: cp stands for copy. This command is used to copy files or group of files or
directory.
If the command contains two file names, then it copy the contents of first file to
the second file. If the second file doesn’t exist, then first it creates one and content is
38

copied to it. But if it exists then it is simply overwritten without any warning.
Page

Syntax: cp sourcefilename destinationfilename

Priyanshu Pandey 2101777 OS


Source file:It is the file whose contents contents are to be copied.
Destination file:It is the file into which the contents of the source file are copied.

3) grep: This command allows you to search for a particular string inside a file or folder.
It returns the whole line containing the phrase if it finds the perfect match.
Syntax: grep string filename (where string stands for the word to be searched).

4) head: The head command lets you read the first ten lines of the content inside a
file.You can also give the names of more than one file in the head command and it
will show the first ten lines of each file separately.You can also change the number of
lines you want to be displayed on the screen rather than the default first ten lines.
Syntax: head -5 filename
The above command will display the first five lines of content from the given file.
39
Page

Priyanshu Pandey 2101777 OS


5) tail: Just like the head command gives you the first ten lines, tail command gives you
the last ten lines of content from the file. Also, you can provide multiple file names to
the tail command for it to show last ten lines from each of the mentioned file.
Similar to the head command, the tail command also allows you to change the number
of lines you want to be displayed other than the default number.
Syntax: tail -1 filename
The above command will display the last fifteen lines of content from the given file.

6) sort : This command is used to sort a file, arranging the records in a particular order.
By default, the sort command sorts file assuming the contents are ASCII. Using
options in sort command, it can also be used to sort numerically.
40

Syntax: sort filename


Page

Priyanshu Pandey 2101777 OS


7) ls: Shows a list of all files.

SECURITY AND PROTECTION COMMANDS


✓ Chmod :
To change mode of the system. It is used to set the three permissions for all the
three categories of users of the files. The owner of the file can only use it.
Syntax: Chmod <category> <operation> <permission> <filename(s)>
Categories Operation Permission
U – user + assign permissions R – read permission
G – group - remove permissions W – write permission
O – others X – execute permission
41

= assign absolute
Page

A - all

Priyanshu Pandey 2101777 OS


PROCESS MANAGEMENT COMMANDS
✓ Ps : PROCESS STATUS
It is used to display the attributes of a process. It has the knowledge of the kernel
built into it. It reads through the kernel data structures or process tables to fetch the
process characteristics. By default, ps lists out the processes associated with a user
at that terminal. Syntax :- ps
Switches :-
-f :- doesnot provide ancestry of process.
-a :- lists out the processes of all users but doesnot display system process.
-u :- lets you know the activities of any user.
-e :- list every process which is active on system.
✓ Kill :
A process an be terminated prematurely by using kill command.
Syntax :- kill 105 it terminates job with PID 105.

INFORMATION COMMANDS
✓ Date :
Tells the system to print the date and time.
Syntax: Date [MM dd hh mm[yy] ]
Switches:
✓ +%D : it shows date as mm/dd/yy.
✓ +%H: shows hours 00-23.
✓ +%M: minutes from 0-59.
✓ Who :
It is use to get information about all users who are currently logged into the
system.
Syntax: Who
User name
✓ Who am i :
User or is getting information about himself.
Syntax: WHO AM I
✓ Echo :
It prints or echoes at the terminal whatever else user happens to type on the line.
Syntax: Echo ‘any line’
✓ Exit :
42

This command is use to terminate a program. The command is


Page

generally run with a numeric argument. Syntax: Exit

Priyanshu Pandey 2101777 OS


✓ Cal :
It comprehends and displays the entire calendar of any year from one A.D to
9999 A.D. Syntax: $ Cal
Cal command displays the current date as well as the calendar (month
proceeding current month itself and month following the current month)
Syntax: $ Cal <month><year>
This syntax displays that month’s calendar only.

FILTER COMMANDS
A filter is a device that reads the standard and writes to the standard
output in a particular format. The format of the output depends on the properties of the
filter.
✓ GREP :
Grep is one of the most useful UNIX filters. It scans a file for the occurrence of
a pattern, and can display the selected pattern, the line numbers in which they are found,
or the filenames where the pattern occurs. Grep can also select lines containing the
pattern.
Syntax : $ grep options patterns filename(s)
E.g. $ grep president emp.lst
OPTIONS :
-c (continuous occurrence) : the –c (count) options counts the occurrences.
-n (displaying line numbers : the –n (number) option can be used to display the
line numbers containing the pattern, along the lines.
-v (deleting lines) : the –v (inverse) option selects all but the lines containing
the pattern.
✓ Cmp:
It is use to comparing two files. It uses two file names as arguments and displays
the difference on the terminal. Syntax: $ Cmp file1 file2
The two files are compared byte-by-byte and the location of the first mismatch
is echoed to the string.
Switches:
–l: list option gives a detailed list of byte number and differing bytes in octal for
each character that differ in both the files.
✓ Comm:
Compares two sorted files (ASCII collating sequence) and compares each line
of the first file with its corresponding line in the second file. Displays the columnar
43

outputs.
Page

Syntax: $ Comm. file1 file2

Priyanshu Pandey 2101777 OS


✓ DIFF :
It is same as cmp. It displays file that consists and also tells which time in one
file have to be changed to make the two files identical. Syntax: $ Diff file1 file2
Switches:
✓ –e: generates a script which when applied to first file will convert to second.
✓ -b: causes trailing blanks to be ignored.

INTER USER & INTER MACHINE COMMANDS


✓ Finger : DETAILS OF USERS
Like who, the finger command also lists login details of a user, but is a more
informative tool.
Syntax : $ finger
When used without arguments, it simply produces a list of all the users logged
on to the system. Unlike who, finger can also provide details about a single user. This
user is logged on to the same machine the command is run on. It also runs in a network
and it can obtain information about remote users.

I/O REDIRECTION & PIPING COMMANDS


Redirection means the input to a command can be taken from a file other than the
user’s terminal keyboard. Similarly, output of command can be written onto a disk file
or onto the printer instead of the screen(VDU). Three types of redirection in unix are :-
✓ > :- output to be stored in directed file not on the user’s terminal.
Syntax :- cat filename1 > filename2
Example:- cat test1 1 > test2 1 means output redirection.
✓ < :- input to be taken from the file .
syntax :- cat < filename
Example :- cat 0 < test 0 means input redirection.

✓ >> :- output to be appended to end of file content and not overwrite.


Syntax :- cat filename1 >> filename2
Example :- cat test1 >> test2

MISCELLANEOUS COMMANDS
✓ Ln :
Files are linked with ln comand with two filenames as arguments.
44

Syntax:- ln file1 file2


Page

Eg:- ln mohit chiku

Priyanshu Pandey 2101777 OS


✓ TOUCH:
To create an empty file on disk.
Syntax: $Touch filename
Touch command is use for following 3 purposes :
a. Creation time
b. Last access time
c. Last modification time
It is use to alter the access time, creation time and modification time.
Switches:
✓ –a : access time
✓ –c : creation time
✓ –m : modification time
If these switches are not there, it updates all the three.
✓ Uname :
You know your machine name by this command.
Syntax:- uname
Switches:-
-n :- machine name in network.
-a :- processor on which version exists.
-v :- version of unix.
✓ SLEEP:
This command puts the system to sleep for a specified number of seconds.
Syntax: $ Sleep time
A shell prompt will appear only after the specified time. Sleep
command is used to retain the output of a particular command for a short period of time before
the screen displays the output of another command.

45
Page

Priyanshu Pandey 2101777 OS


5. Shell Programming: Basic of shell programming, various types of shell, Shell
programming in bash, conditional & looping statement, case statements, parameter
passing and arguments, shell variables, shell keywords, creating shell programs for
automate system tasks, report printing.

SHELL PROGRAMMING
A shell program runs in interpretive mode. It is not compiled to a separate executable file as a
C program is. Each statement is loaded into memory when it is to be executed. Shell scripts
consequently run slower than those written in high-level languages. Speed is not a factor in
many jobs we do, and in many cases, using the shell in an advantages- especially in system
administrative tasks. The Unix system administrator must be accomplished shell programmer.

SHELL SCRIPTS
When a group of command have to be executed regularly, they should be stored in a file, and
the file itself executed as a shell script or shell program. Though it’s not mandatory, we
normally use the .sh extension for shell scripts. Shell scripts are executed in a separate child
shell process, and this sub-shell need not be the same as your login shell. By default, the child
and parent shells belongs to the same type, but you can provide a special interpreter line in the
first line of the script to specify a different shell for your script. Use your vi editor to create the
shell script, script.sh.

EDITOR COMMANDS

Editors :
In an operating system, a editor is assumed authority which helps to create and modify
users files in data. Any ASCII text files such as a program or a document may be created
or modified using a text editor. There are three text editors present under UNIX i.e.
❑ Ed - line editor
❑ Vi - Screen editor
❑ Sed - Stream editor

* Ed :
It is just a line editor, like edlin in DOS. It is an older standard Unix editor originally written
by Ken Thompson and available on every Unix system. It takes no advantage on special
terminal features. So it can work on any terminal. It also forms the basis of other essential
programs. Ed was designed in early 1970's for a computing environment and was derived
from an earlier editor called Qed. Syntax : ed <filename>

*VI EDITOR :
UNIX provides a very versatile one—vi. Bill Joy created this editor for the BSD system. The
program is now standard on all the UNIX system. Vi uses a number of internal commands to
navigate to any point in a text file and edit the text there. It also allows you to copy and move
text within a file and also from one file to another. Vi offers cryptic, and sometimes
mnemonic, internal commands for editing work. MODES USED BY VI :
46
Page

Priyanshu Pandey 2101777 OS


*COMMAND MODE :
The default mode of the editor where every key is interpreted as a command to run on text.
You will have to be in this mode to copy and delete text. Unnecessary pressing of Esc in this
mode sounds a beep but also confirms that you are in this mode.

*INPUT MODE :
Every key pressed after switching to this mode actually shows up as text. Pressing Esc in this
mode takes vi to command mode.

COMMAND FUNCTION
I Inserts text to left of cursors.
A Appends text to right of cursor.
I Inserts text at beginning of line.
A Appends text at end of line.
O Opens line below.
O Opens line above.
Replaces single character under cursor with ch
rch
(No [Esc] required).
Replaces single character under cursor with any number of
R
characters.
Replaces single character under cursor with any number of
S
characters.
S Replaces entire line.

*EX MODE OR last line mode :


The mode used to handle files and perform substitution. Pressing a: in the command mode
invokes this mode. You then enter an ex mode command follows by [Enter]. After the
command is run, you are back to the default command mode.

COMMAND ACTION
:w Saves file and remains in editing mode.
:x Saves file and quits editing mode.
:wq As above.
:w n2w.p1 Like Save As …. In Microsoft windows.
:w! n2w.p1 As above, but overwrites existing file.
47

:q Quits editing mode when no changes are made to file.


Page

Priyanshu Pandey 2101777 OS


:q! Quits editing mode but after abandoning changes.
:n1,n2w
Write lines n1 to n2 to file build.sql.
build.sql
:.w build.sql Write current line to file build.sql.
:$w build.sql Write last line to file build.sql.
:sh Escapes to UNIX shell.
:recover Recovers file from a crash.

*NAVIGATION:
In this we consider the command mode. This is the mode you come to when you have finished
entering or changing your text. A Command Mode command doesn’t show up on screen but
simply performs a function. We begin with navigation. Don’t forget to avoid the cursors control
keys for navigation.

KEY FUNCTION
K Moves cursor up.
J Moves cursor down.
H Moves cursor left.
SL Moves cursor right.
B Moves back to the beginning of word.
E Moves forward to the beginning of word.
W Moves forward to the end of word.
O Moves the cursor to the positioned column.
$ Moves to the end of line.
G Goes to end of file.

*EDITING TEXT:
The editing facilities in vi are very elaborate and involve the use of operators.
Keys for Editing Text :

KEY FUNCTION
48

d Delete
Page

Priyanshu Pandey 2101777 OS


y Yank (Copy)
x Deletes a single character
dd Removes the entire line.
P/p Put the text at the new location with p or P.
yy Yanks (copy) current line
Removes the new-line character between two lines to pull up line
J
below it

49
Page

Priyanshu Pandey 2101777 OS


SHELL PROGRAMS

5a. To create a script to enter a string and then print its manipulation table.

$ cat table.sh
# To print multiplication table
echo "Enter a number for which the multiplication table is to be written "
read number1
echo "The length up to which table is to be written "
read number2
echo "Multiplication table for" $number1 " is given below "
count=1
while [ $count -le $number2 ]
do
result=`expr $number1 \* $count`
echo $count "*" $number1 "=" $result
count=`expr $count + 1`
done

OUTPUT :

$ sh table.sh
Enter a number for which the multiplication table is to be written
2
The length upto which table is to be written
10
Multiplication table for 2 is given below
1*2=2
2*2=4
3*2=6
4*2=8
5 * 2 = 10
6 * 2 = 12
7 * 2 = 14
8 * 2 = 16
9 * 2 = 18
10 * 2 = 20
50
Page

Priyanshu Pandey 2101777 OS


5b. To create a script to accept a number and compute it's factorial.

$ cat factorial.sh
# To compute the factorial
echo "Enter the number whose factorial is to be computed"
read num
temp=`expr $num - 1`
while [ $temp -ge 1 ]
do
num=`expr $num \* $temp`
temp=`expr $temp - 1`
done
echo "The factorial of number is : $num"

OUTPUT :

$ sh factorial.sh
Enter the number whose factorial is to be computed
5
The factorial of number is : 120

51
Page

Priyanshu Pandey 2101777 OS


5c. Write a script to determine whether a given number is prime or not.

$ cat prime.sh
# To find the number is prime or not
echo "Enter no: "
read num
i=2
while [ $i –le $num ]
do
if [ `expr $num % $i ` –eq 0 ]
then
break
fi
i=`expr $i + 1`
done
if [ $i -eq $num ]
then
echo "$num is a prime number"
else
echo "$num is not a prime number"
fi

OUTPUT :

$ sh prime.sh
Enter no:
4
4 is not a prime no.

$ sh prime.sh
Enter no:
7
7 is a prime number
52
Page

Priyanshu Pandey 2101777 OS


5d. Write a shell script to find out whether the number entered is odd or even.

$ cat odd.sh
# check whether the entered number is even or odd
echo "Enter a no.: "
read n
x=`expr $n % 2`
if [ $x -eq 0 ]
then
echo "EVEN"
else
echo "ODD"
fi

OUTPUT :

$ sh odd.sh
Enter a no.:
2
EVEN

$ sh odd.sh
Enter a no.:
15
ODD

53
Page

Priyanshu Pandey 2101777 OS


5e. To Create a shell script ‘add phone’ that asks a user for a name and then a phone
Number.
The name and phone number will be put in a file
# ‘phonebook’. You should be able to run ‘add phone’ several times without
# destroying the previous contents of ‘phonebook’.

# cat addphone.sh
# To enter a list of names
c=1
while [ $c –eq 1 ]
do
echo "Please enter the name of person"
read name
echo "Please enter the phone number of person"
read phone
echo $name >> phonebook
echo $phone >> phonebook
echo "Press 1 to continue , 2 to exit"
read c
done

OUTPUT :

$ sh addphone.sh
Please enter the name of person Deepak
Please enter the phone number of person 3957417
Press 1 to continue , 2 to exit 1
Please enter the name of person Rahul
Please enter the phone number of person 9888165135
Press 1 to continue , 2 to exit 1
Please enter the name of person Rohit
Please enter the phone number of person 9872821444
Press 1 to continue , 2 to exit 2

$ cat phonebook
Deepak
3957417
Rahul
9888165135
Rohit
9872821444
54
Page

Priyanshu Pandey 2101777 OS


6. Implementation of Bankers algorithm for the purpose of deadlock avoidance

Algorithm:

Available:
• It is a 1-d array of size ‘m’ indicating the number of available resources of each type.
• Available[ j ] = k means there are ‘k’ instances of resource type Rj

Max:
• It is a 2-d array of size ‘n*m’ that defines the maximum demand of each process in a
system.
• Max[ i, j ] = k means process Pi may request at most ‘k’ instances of resource type Rj.

Allocation:
• It is a 2-d array of size ‘n*m’ that defines the number of resources of each type
currently allocated to each process.
• Allocation[ i, j ] = k means process Pi is currently allocated ‘k’ instances of resource
type Rj

Need:
• It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of each
process.
• Need [ i, j ] = k means process Pi currently need ‘k’ instances of resource type Rj
for its execution.
• Need [ i, j ] = Max [ i, j ] – Allocation [ i, j ]

Program:

#include <iostream>

using namespace std;

int main()

// P0, P1, P2, P3, P4 are the Process names here

int n, m, i, j, k;

n = 5; // Number of processes

m = 3; // Number of resources
55

int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix


Page

{ 2, 0, 0 }, // P1

Priyanshu Pandey 2101777 OS


{ 3, 0, 2 }, // P2

{ 2, 1, 1 }, // P3

{ 0, 0, 2 } }; // P4

int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix

{ 3, 2, 2 }, // P1

{ 9, 0, 2 }, // P2

{ 2, 2, 2 }, // P3

{ 4, 3, 3 } }; // P4

int avail[3] = { 3, 3, 2 }; // Available Resources

int f[n], ans[n], ind = 0;

for (k = 0; k < n; k++) {

f[k] = 0;

int need[n][m];

for (i = 0; i < n; i++) {

for (j = 0; j < m; j++)

need[i][j] = max[i][j] - alloc[i][j];

int y = 0;

for (k = 0; k < 5; k++) {

for (i = 0; i < n; i++) {

if (f[i] == 0) {

int flag = 0;

for (j = 0; j < m; j++) {

if (need[i][j] > avail[j]){

flag = 1;
56
Page

break;

Priyanshu Pandey 2101777 OS


}

if (flag == 0) {

ans[ind++] = i;

for (y = 0; y < m; y++)

avail[y] += alloc[i][y];

f[i] = 1;

cout << "Following is the SAFE Sequence" << endl;

for (i = 0; i < n - 1; i++)

cout << " P" << ans[i] << " ->";

cout << " P" << ans[n - 1] <<endl;

return (0);

Output:

57
Page

Priyanshu Pandey 2101777 OS

You might also like