You are on page 1of 20

4.

Implementation of FCFS Scheduling algorithm

FCFS (First-Come-First-Serve) scheduling is a simple CPU scheduling algorithm. In


this algorithm, processes are executed in the order they arrive in the ready queue.
The implementation of the FCFS scheduling algorithm can be done as follows:

Implementation:

1- Input the processes along with their burst time (bt).


2- Find waiting time (wt) for all processes.
3- As first process that comes need not to wait so
waiting time for process 1 will be 0 i.e. wt[0] = 0.
4- Find waiting time for all other processes i.e. for
process i ->
wt[i] = bt[i-1] + wt[i-1] .
5- Find turnaround time = waiting_time + burst_time
for all processes.
6- Find average waiting time =
total_waiting_time / no_of_processes.
7- Similarly, find average turnaround time =
total_turn_around_time / no_of_processes.

Implementation of code:

// C++ program for implementation of FCFS


// scheduling
#include<iostream>
using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;
}

// Function to calculate turn around time


void findTurnAroundTime( int processes[], int n,
int bt[], int wt[], int tat[])

17
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

//Function to calculate average time


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

//Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes


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

//Display processes along with all details


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

// Calculate total waiting time and total turn


// around time
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;
}

// Driver code
int main()
{
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

//Burst time of all processes


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

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

18
Output:
Processes Burst time Waiting time Turn around time

1 10 0 10

2 5 10 15

3 8 15 23

Average waiting time = 8.33333

Average turn around time = 16

19
5. Implementation of SJF Scheduling algorithm

The Shortest Job First (SJF) Scheduling algorithm is a non-preemptive scheduling


algorithm that schedules processes based on their burst time. In this algorithm, the
process with the shortest burst time is executed first, and if multiple processes have
the same burst time, the process with the lowest arrival time is executed first. Here's
an implementation of the SJF scheduling algorithm in C++.

#include <iostream>
using namespace std;

int main() {

// Matrix for storing Process Id, Burst


// Time, Average Waiting Time & Average
// Turn Around Time.
int A[100][4];
int i, j, n, total = 0, index, temp;
float avg_wt, avg_tat;

cout << "Enter number of process: ";


cin >> n;

cout << "Enter Burst Time:" << endl;

// User Input Burst Time and alloting Process Id.


for (i = 0; i < n; i++) {
cout << "P" << i + 1 << ": ";
cin >> A[i][1];
A[i][0] = i + 1;
}

// Sorting process according to their Burst Time.


for (i = 0; i < n; i++) {
index = i;
for (j = i + 1; j < n; j++)
if (A[j][1] < A[index][1])
index = j;
temp = A[i][1];
A[i][1] = A[index][1];
A[index][1] = temp;

temp = A[i][0];
A[i][0] = A[index][0];
A[index][0] = temp;
}

A[0][2] = 0;
// Calculation of Waiting Times

20
for (i = 1; i < n; i++) {
A[i][2] = 0;
for (j = 0; j < i; j++)
A[i][2] += A[j][1];
total += A[i][2];
}

avg_wt = (float)total / n;
total = 0;
cout << "P BT WT TAT" << endl;

// Calculation of Turn Around Time and printing the


// data.
for (i = 0; i < n; i++) {
A[i][3] = A[i][1] + A[i][2];
total += A[i][3];
cout << "P" << A[i][0] << " " << A[i][1] << " " << A[i][2] << " " << A[i][3] << endl;
}

avg_tat = (float)total / n;
cout << "Average Waiting Time= " << avg_wt << endl;
cout << "Average Turnaround Time= " << avg_tat << endl;
}

Output:
Enter number of process: 4

Enter Burst Time:

P1: 5,P2: 3, P3: 4, P4: 6

P BT WT TAT

P2 3 0 3

P3 4 3 7

P1 5 7 12

P4 6 12 18

Average Waiting Time= 5.5

Average Turnaround Time= 10

21
6. Implementation of Round-Robin Scheduling
algorithm
// C++ program for implementation of RR scheduling
#include<iostream>
using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[], int quantum)
{
// Make a copy of burst times bt[] to store remaining
// burst times.
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

int t = 0; // Current time

// Keep traversing processes in round robin manner


// until all of them are not done.
while (1)
{
bool done = true;

// Traverse all processes one by one repeatedly


for (int i = 0 ; i < n; i++)
{
// If burst time of a process is greater than 0
// then only need to process further
if (rem_bt[i] > 0)
{
done = false; // There is a pending process

if (rem_bt[i] > quantum)


{
// Increase the value of t i.e. shows
// how much time a process has been processed
t += quantum;

// Decrease the burst_time of current process


// by quantum
rem_bt[i] -= quantum;
}

// If burst time is smaller than or equal to


// quantum. Last cycle for this process
else
{

22
// Increase the value of t i.e. shows
// how much time a process has been processed
t = t + rem_bt[i];

// Waiting time is current time minus time


// used by this process
wt[i] = t - bt[i];

// As the process gets fully executed


// make its remaining burst time = 0
rem_bt[i] = 0;
}
}
}

// If all processes are done


if (done == true)
break;
}
}

// Function to calculate turn around time


void findTurnAroundTime(int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

// Function to calculate average time


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

// Function to find waiting time of all processes


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

// Function to find turn around time for all processes


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

// Display processes along with all details


cout << "PN\t "<< " \tBT "
<< " WT " << " \tTAT\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];

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

// Driver code
int main()
{
// process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

// Burst time of all processes


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

// Time quantum
int quantum = 2;
findavgTime(processes, n, burst_time, quantum);
return 0;
}

Output:
PN BT WT TAT

1 10 13 23

2 5 10 15

3 8 13 21

Average waiting time = 12

Average turn around time = 19.6667

24
7. What is vi editor and its commands?

The vi editor is elaborated as visual editor. It is installed in every Unix system. In other words,
it is available in all Linux distros. It is user-friendly and works same on different distros and
platforms. It is a very powerful application. An improved version of vi editor is vim.

The vi editor has two modes:


o Command Mode: In command mode, actions are taken on the file. The vi editor
starts in command mode. Here, the typed words will act as commands in the vi editor.
To pass a command, you need to be in command mode.
o

o Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key
will take you to the command mode from insert mode.
By default, the vi editor starts in command mode. To enter text, you have to be in insert
mode, just type 'i' and you'll be in insert mode. Although, after typing i nothing will appear
on the screen but you'll be in insert mode. Now you can type anything.

Using vi
The vi editor tool is an interactive tool as it displays changes made in the file on the screen
while you edit the file.

In vi editor you can insert, edit or remove a word as cursor moves throughout the file.

Commands are specified for each function like to delete it's x or dd.

The vi editor is case-sensitive. For example, p allows you to paste after the current line
while P allows you to paste before the current line.

Command mode
This is what you'll see when you'll press enter after the above command. If you'll start typing,
nothing will appear as you are in command mode. By default vi opens in command mode.

25
Look at the above snapshot, it is blank as it is a new file. To start typing, you have to move to
the insert mode. At the end of the terminal window, directory name and file name are
displayed.

Insert mode
To move to the insert mode press i. Although, there are other commands also to move to
insert mode which we'll study in next page.

Look at the above snapshot, after pressing i we have entered into insert mode. Now we can
write anything. To move to the next line press enter.
Once you have done with your typing, press esc key to return to the command mode.

To save and quit


You can save and quit vi editor from command mode. Before writing save or quit command
you have to press colon (:). Colon allows you to give instructions to vi.
exit vi table:

Commands Action

:wq Save and quit

:w Save

:q Quit

:w fname Save as fname

ZZ Save and quit

:q! Quit discarding changes made

:w! Save (and write to non-writable file)

26
Look at the above snapshot, command :wq will save and quit the vi editor. When you'll type
it in command mode, it will automatically come at bottom left corner.
If you want to quit without saving the file, use :q. This command will only work when you
have not made any changes in the file.

Vi Commands
Linux vi editor is different from other editors. You have to use different keys to use different
functions. Although, it's quite easy and interesting to use vi editor.
The vi editor commands are case sensitive.
Have a look at the vi commands in the following table.

To switch from command to insert mode:

Command Action

i Start typing before the current character

I Start typing at the start of current line

a Start typing after the current character

A Start typing at the end of current line

o Start typing on a new line after the current line

O Start typing on a new line before the current line

To move around a file:


27
Commands Action

j To move down

k To move up

h To move left

l To move right

To jump lines:

Commands Action

G Will direct you at the last line of the file

`` Will direct you to your last position in the file

To delete:

Commands Action

x Delete the current character

X Delete the character before the cursor

r Replace the current character

xp Switch two characters

dd Delete the current line

D Delete the current line from current character to the end of the line

dG delete from the current line to the end of the file

28
8. Shell Commands

1) To view a single file Command:

-> $cat filename

2) To view multiple files

-> $cat file1 file2

3) To view contents of a file preceding with line numbers.

-> $cat -n filename

4) Create a file

-> $ cat > newfile

5) Copy the contents of one file to another file.

-> $cat [filename-whose-contents-is-to-be-copied] > [destination-filename]

6) Cat command can suppress repeated empty lines in output

-> $cat -s geeks.txt

7) Cat command can append the contents of one file to the end of another file.

-> $cat file1 >> file2

29
9. Shell Scripting- Using variables

Variable Names-:
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the
underscore character ( _).

By convention, Unix shell variables will have their names in UPPERCASE.

Defining Variables
Variables are defined as follows −

-> variable_name=variable_value

For example −

-> NAME="Zara Ali"

SYNTAX-:

NAME="RAJAT"
echo $NAME
VAR2=100
echo $VAR2

OUTPUT-:
RAJAT

100

30
10. Shell Scripting- - Input & Output

Input from the user:

You can use the "read" command to prompt the user to enter input. The input can be
stored in a variable, which can then be used in the script. For example, the following
code prompts the user to enter their name and then displays a greeting message:

echo "What is your name?"


read name
echo "Hello, $name!"

Output to the screen:

You can use the "echo" command to display output on the screen. For example, the
following code displays a message:

echo "Hello, world!"

Output to a file:

You can use the ">" symbol to redirect output to a file. For example, the following
code writes the output of the "ls" command to a file called "files.txt":

ls > files.txt

31
11. Shell Scripting- Data types

In shell scripting, there are three main data types:

Strings: Strings are a sequence of characters, enclosed within single or double


quotes. They can contain letters, numbers, and special characters.

Integers: Integers are whole numbers without decimal points, positive or negative.
They are used for performing arithmetic operations.

Floats: Floats are numbers with decimal points. They are also used for performing
arithmetic operations, but they have limited precision compared to other
programming languages.

!/bin/bash

# String variable
name="John"

# Integer variable
age=30

# Float variable
height=1.75

echo "My name is $name, I am $age years old, and my height is $height
meters."

32
12. Shell Scripting- Use of arithmetic operators

1. Addition (+): Adds two values together.

Example: sum=$((10+20))

2. Subtraction (-): Subtracts one value from another.

Example: difference=$((30-20))

3. Multiplication (*): Multiplies two values together.

Example: product=$((5*6))

4. Division (/): Divides one value by another.

Example: quotient=$((30/5))

5. Increment (++): Increases the value of a variable by 1.

Example: remainder=$((25%3))

6. Decrement (--): Decreases the value of a variable by 1.

Example: count=0
count++

33
13. Shell Scripting- if control statement
programs

1. Check if a file exists:

```
#!/bin/bash

if [ -e "/path/to/file" ]
then
echo "File exists"
else
echo "File does not exist"
fi
```

2. Check if a user exists:

```
#!/bin/bash

if id "username" >/dev/null 2>&1


then
echo "User exists"
else
echo "User does not exist"
fi
```

34
14. Shell Scripting- while control statement
The `while` loop is a control structure used in shell scripting to execute a set of
commands repeatedly until a certain condition is met. The syntax for the `while` loop
in shell scripting is as follows:

```
while [ condition ]
do
# commands to be executed
done
```

Here, the `condition` is a logical expression that must evaluate to true (i.e., non-zero) or false
(i.e., zero) value. The `do` keyword starts the block of commands to be executed, and the
`done` keyword marks the end of the loop.

The `while` loop continues to execute the commands within the loop as long as the
`condition` remains true. When the `condition` becomes false, the loop terminates, and the
control transfers to the statement following the `done` keyword.

Here's an example of a shell script that uses a `while` loop to print numbers from 1 to 10:

#!/bin/bash

count=1

while [ $count -le 10 ]


do
echo $count
count=$((count+1))
done

echo "Loop executed successfully."


```

35
15. Shell Scripting- for control statement

In shell scripting, the `for` statement is used to iterate through a sequence of values
and perform a set of commands for each value. The syntax of the `for` statement is
as follows:

```
for variable in sequence
do
commands
done
```

Here, `variable` is a placeholder for the current value in the sequence being
processed, and `sequence` is a list of values or expressions that can be expanded
into a list of values.

For example, consider the following shell script that uses a `for` statement to iterate
through a list of filenames and perform a set of commands for each file:

```
#!/bin/bash

for file in *.txt


do
echo "Processing file: $file"
cat $file | grep "pattern"
done
```

36

You might also like