Os Programs Reference Material
Os Programs Reference Material
OPERATING SYSTEM
Lab Manual (CSE18R273)
Student Name :
Register Number :
Section :
1
TABLE OF CONTENTS
1 Bonafide Certificate 3
3 Course Plan 5
4 Introduction 10
Experiments
2
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
BONAFIDE CERTIFICATE
academic year .
Submitted to the practical Examination held at Kalasalingam Academy of Research and Education,
Anandnagar, Krishnankoil on
REGISTER NUMBER
10 Implementation of Cryptographic
Algorithms
4
BASIC LINUX COMMANDS
AIM:
COMMANDS DESCRIPTION:
5
EXECUTION & OUTPUT:
6
7
Result: The general purpose utility commands was executed successfully.
Algorithm
Program
Output
Viva
8
Ex. No. 1b General Purpose Utility Commands
AIM:
To work with some of the general purpose utility commands in UNIX.
COMMANDS DESCRIPTION:
9
EXECUTION & OUTPUT:
10
Result : The general purpose utility commands was executed successfully.
Algorithm
Program
Output
Viva
11
SYSTEM CALLS
Ex. No. 2a Fork System Call
AIM:
To write a program to create a child process using the system calls –fork.
ALGORITHM:
1. fork() to create a child process from the main/parent process
The fork() system function does not accept any argument. It returns an integer of the type pid_t.
On success, fork() returns the PID of the child process which is greater than 0. Inside the child
process, the return value is 0. If fork() fails, then it returns -1.
2. print the PID (Process ID) and PPID (Parent Process ID) from child and parent process.
3. On the parent process wait(NULL) is used to wait for the child process to finish
4. On the child process, exit() is used to finish the child process.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
pid_t pid = fork();
if(pid == 0) {
printf("Child => PPID: %d PID: %d\n", getppid(), getpid());
exit(EXIT_SUCCESS);
}
else if(pid > 0) {
12
printf("Parent => PID: %d\n", getpid());
printf("Waiting for child process to finish.\n");
wait(NULL);
printf("Child process finished.\n");
}
else {
13
Result : Hence create a child process using the system calls – fork executed successfully
Algorithm
Program
Output
Viva
14
Ex. No. 2b EXEC System Call
AIM:
To write a program to display time and date using exec system call.
ALGORITHM
execlp("date","date", NULL);
execv("./hello", args);
printf("Back to example.c");
return 0;
}
15
Result: Thus to display time and date using exec system call was executed successfully.
Algorithm
Program
Output
Viva
16
Ex.No. 2c STAT System Call
DESCRIPTION:
stat() is a Unix system call that returns file attributes about an inode. The semantics
of stat() vary between operating systems. As an example, Unix command ls uses this system call to
retrieve information on files that includes:
AIM:
ALGORITHM:
link, then it returns information about the link itself, not the file
17
that the link refers to.
fd.
All of these system calls return a stat structure, which contains the
following fields:
struct stat {
18
/* Since Linux 2.6, the kernel supports nanosecond
PROGRAM:
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
exit(EXIT_FAILURE);
19
}
20
printf("Preferred I/O block size: %ld bytes\n",
(long) sb.st_blksize);
exit(EXIT_SUCCESS);
}
21
Result: Thus program to implement STAT system call was implemented successfully.
Algorithm
Program
Output
Viva
22
Ex. No. 2d Wait System Call
DESCRIPTION:
The system call wait() is blocks the calling process until one of its child processes exits or
a signal is received. For our purpose, we shall ignore signals. wait() takes the address of an integer
variable and returns the process ID of the completed process. Some flags that indicate the
completion status of the child process are passed back with the integer pointer. One of the main
purposes of wait() is to wait for completion of child processes.
1. If there are at least one child processes running when the call to wait() is made, the caller
will be blocked until one of its child processes exits. At that moment, the caller resumes its
execution.
2. If there is no child process running when the call to wait() is made, then this wait() has no
effect at all. That is, it is as if no wait() is there.
AIM:
To write a program using wait system call
ALGORITHM:
1.print before fork. Then fork() system call creates a child process.
2.wait() system call is added to the parent section of the code.
3. Hence, the moment processor starts processing the parent, the parent process is suspended
because the very first statement is wait(NULL).
4. Thus,
first, the child process runs, and the output lines are all corresponding to the child process.
Once the child process finishes, parent resumes and prints all its printf() statements.
5. The NULL inside the wait() means that we are not interested to know the status of change of
state of child process
PROGRAM:
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
23
#include<sys/wait.h>
int main()
{
pid_t p;
printf("before fork\n");
p=fork();
if(p==0)//child
{
printf("I am child having id %d\n",getpid());
printf("My parent's id is %d\n",getppid());
}
else//parent
{
wait(NULL);
printf("My child's id is %d\n",p);
printf("I am parent having id %d\n",getpid());
}
printf("Common\n");
24
EXECUTION & OUTPUT:
Algorithm
Program
Output
Viva
Result : Thus program using wait system call was executed successfully
25
Ex. No. 2e Input Output system Call
DESCRIPTION:
- creat(name, permissions) – Used to create a file with the name and mode specified. Here,
permission would be a number. 0666 means read write permissions.
- open(name, mode) – Used to open a file name in the mode (read or write) specified. 0 is for
opening in read mode, 1 for writing and 2 for both.
- lseek(fd, offest, whence) - Move the read/write pointer to the specified location.
AIM:
26
6. int open (const char* Path, int flags [, int mode ]);
Parameters
Path : path to file which you want to use
use absolute path begin with /, when you are not work in same directory of file.
Use relative path which is only file name with extension, when you are work in same directory of
file.
flags : How you like to use
O_RDONLY: read only, O_WRONLY: write only, O_RDWR: read and write, O_CREAT: create
file if it doesnt exist, O_EXCL: prevent creation if it already exists
How it works in OS
7.Find existing file on disk
8.Create file table entry
PROGRAM:
// C program to illustrate
// open system call
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
extern int errno;
int main()
{
// if file does not have in directory
// then file foo.txt is created.
int fd = open("foo.txt", O_RDONLY | O_CREAT);
int close(int fd);
printf("fd = %d/n", fd);
27
if (fd ==-1)
{
// print which type of error have in a code
printf("Error Number % d\n", errno);
}
return 0;
}
EXECUTION & OUTPUT:
28
Result : Thus program to implement the concept of I/O call was executed successfully.
Algorithm
Program
Output
Viva
29
SCHEDULING ALGORITHMS
AIM:
To write a program using C in UNIX environment to implement the first come first serve
scheduling.
ALGORITHM:
Step1: Create the number of process.
Step2: Get the ID and Service time for each process.
Step3: Initially, Waiting time of first process is zero and Total time for the first process is the
starting time of that process.
Step4: Calculate the Total time and Processing time for the remaining processes. Step5: Waiting
time of one process is the Total time of the previous process.
Step6: Total time of process is calculated by adding Waiting time and Service time. Step7: Total
waiting time is calculated by adding the waiting time for lack process. Step8: Total turn around
time is calculated by adding all total time of each process.
Step9: Calculate Average waiting time by dividing the total waiting time by total number of
process.
Step10: Calculate Average turn around time by dividing the total time by the number of process.
Step11: Display the result
PROGRAM:
#include<stdio.h>
struct process
{
int id,wait,ser,tottime;
}p[20];
main()
{
30
int i,n,j,totalwait=0,totalser=0,avturn,avwait;
printf("Enter number of process:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter process_id:");
scanf("%d",&p[i].id);
{
for(j=1;j<i;j++)
{
p[i].wait=p[i].wait+p[j].ser;
}
totalwait=totalwait+p[i].wait;
p[i].tottime=p[i].wait+p[i].ser;
totalser=totalser+p[i].tottime;
}
avturn=totalser/n;
avwait=totalwait/n;
printf("Id\tservice\twait\ttotal");
for(i=1;i<=n;i++)
{
printf("\n%d\t%d\t%d\t%d\n",p[i].id,p[i].ser,p[i].wait,p[i].tottime);
31
}
printf("average waiting time %d\n",avwait);
printf("average turnaround time %d\n",avturn);
}
Result: Thus the C program to implement CPU scheduling algorithm for first come first serve was
executed successfully
Algorithm
Program
Output
Viva
32
Ex. No. 3b Shortest Job First Scheduling
AIM:
To write a program using C in UNIX environment to implement the shortest job next
concept.
ALGORITHM:
Step8:Total turn around time calculated by adding all total time of each process.
Step9:calculate average waiting time by dividing the total waiting time by total number of process.
Step10:Calculate average turn around time by dividing the total waiting time by total number of
process.
Step11:Display the result
PROGRAM:
#include<stdio.h>
struct ff
{
int pid,ser,wait;
}p[20];
33
struct ff tmp;
main()
{
int i,n,j,tot=0,avwait,totwait=0,tturn=0,aturn;
printf("enter the number of process");
scanf("%d",&n);
for(i=0;i<n;i++)
{
{
for(j=i+1;j<n;j++)
{
if(p[i].ser>p[j].ser)
{
tmp=p[i]; p[i]=p[j]; p[j]=tmp;
}
}
}
printf("PID\tSER\tWAIT\tTOT\n");
for(i=0;i<n;i++)
{
tot=tot+p[i].ser;
34
tturn=tturn+tot;
p[i+1].wait=tot;
totwait=totwait+p[i].wait;
printf("%d\t%d\t%d\t%d\n",p[i].pid,p[i].ser,p[i].wait,tot);
}
avwait=totwait/n;
aturn=tturn/n;
Result : Thus the C program to implement the CPU scheduling algorithm for shortest job
first was executed successfully.
35
Ex. No. 3c Round Robin Scheduling
AIM:
To write a program using C in UNIX environment to implement Round-robin scheduling
concept.
ALGORITHM:
Step 2: Receive inputs from the user to fill process id,burst time and arrival time.
Step 3: Calculate the waiting time for all the process id.
a) If the time quantum is greater than the remaining burst time then
waiting time is calculated as:
a[i].waittime=count + tq
b) Else if the time quantum is greater than the remaining burst
time then waiting time is calculated as:
a[i].waittime=count - remaining burst time
Step 4: Calculate the average waiting time and average turnaround time
Step 5: Print the results of the step 4.
PROGRAM:
#include <stdio.h>
struct roundRobin
{
int pburst,pburst1,wtime,endtime,arrivt,boolean,flagcntl; char pname[5];
}a[5];
36
int n,tq;
void input();
void initialize();
void calculate();
void display_waittime();
int main()
{
input();
initialize();
calculate();
display_waittime();
//getch();
//return 0;
}
void input()
{
int i;
printf("Enter Total no. of processes\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
37
printf("\nEnter the time quantum/Time Slice:");
scanf("%d",&tq);
}
void initialize()
{ int i;
for(i=0;i<n;i++)
{
a[i].pburst1=a[i].pburst;
a[i].wtime=0;
a[i].endtime=0;
a[i].boolean=0;
a[i].flagcntl=0;
}
void calculate()
{
int i,j=0,k=0,flag=1,count=0;
printf("\n---GANTT CHART---\n");
printf("0 | ");
while(flag)
{
for(i=0;i<n;i++)
{
if((k<n)&&(a[i].arrivt<=count)&&(a[i].flagcntl==0)) //calculating waiting time for first time
{
38
a[i].wtime=count-a[i].arrivt;
a[i].endtime=count;
a[i].boolean=1;
a[i].flagcntl=1;
k++;
}
if((a[i].pburst1>tq)&&(a[i].arrivt<=count))
{
if(a[i].boolean==1)
a[i].boolean=0;
else
a[i].wtime=a[i].wtime+(count-a[i].endtime);
count=count+tq;
a[i].pburst1=a[i].pburst1-tq; a[i].endtime=count;
printf("%d %s| ",count,a[i].pname);
}
else if((a[i].pburst1>0) && (a[i].pburst1<=tq) && (a[i].arrivt<=count))
if(a[i].boolean==1)
a[i].boolean=0;
else
a[i].wtime=a[i].wtime+(count-a[i].endtime);
count=count+a[i].pburst1;
a[i].endtime=count;
39
else if(j==n) flag=0;
}//end of for loop
}//end of while loop
void display_waittime()
{
int i,tot=0,turn=0;
for(i=0;i<n;i++)
{
printf("\n\nWaiting time for Process %s is %d",a[i].pname,a[i].wtime);
tot=tot+a[i].wtime;
turn=turn+a[i].endtime-a[i].arrivt;
}
40
Result: Thus the C program to simulate CPU scheduling algorithm for round robin was executed
successfully.
Algorithm
Program
Output
Viva
41
Ex.No. 3d Priority Scheduling
AIM:
Step 2: Declare the variable i,j as integer, totwtime and totttime is equal to zero.
Step 3: Get the value of „n‟ assign p and allocate the memory.
Step 4: Inside the for loop get the value of burst time and priority.
Step 5: Assign wtime as zero .
Step 6: Check p[i].pri is greater than p[j].pri .
Step 7: Calculate the total of burst time and waiting time and assign as turnaround time.
Step 8: Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int et[20],at[10],n,i,j,temp,p[10],st[10],ft[10],wt[10],ta[10];
int totwt=0,totta=0;
float awt,ata;
char pn[10][10],t[10];
//clrscr();
printf("Enter the number of process:");
scanf("%d",&n);
42
for(i=0; i<n; i++)
{
printf("Enter process name,arrivaltime,execution time & priority:");
//flushall();
scanf("%s%d%d%d",pn[i],&at[i],&et[i],&p[i]);
}for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(p[i]<p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}
}
for(i=0; i<n; i++)
43
if(i==0)
{
st[i]=at[i];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
else
{
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttatime");
for(i=0; i<n; i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],p[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
getch();
}
44
EXECUTION & OUTPUT:
Result : Thus the C program to implement the priority scheduling algorithm was executed
successfully
Algorithm
Program
Output
Viva
45
Ex.No : 4 SIMULATATION of IPC in UNIX
AIM:
DESCRIPTION:
In the discussion of the fork() system call, we mentioned that a parent and its children have
separate address spaces. While this would provide a more secured way of executing parent and
children processes (because they will not interfere each other), they shared nothing and have no
way to communicate with each other. A shared memory is an extra piece of memory that is
attached to some address spaces for their owners to use. As a result, all of these processes share
the same memory segment and have access to it. Consequently, race conditions may occur if
memory accesses are not handled properly. The following figure shows two processes and their
address spaces. The yellow rectangle is a shared memory attached to both address spaces and both
process 1 and process 2 can have access to this shared memory as if the shared memory is part of
its own address space. In some sense, the original address spaces is "extended" by attaching this
shared memory.
Shared memory is a feature supported by UNIX System V, including Linux, SunOS and Solaris.
One process must explicitly ask for an area, using a key, to be shared by other processes. This
process will be called the server. All other processes, the clients, that know the shared area can
access it. However, there is no protection to a shared memory and any process that knows it can
access it freely. To protect a shared memory from being accessed at the same time by several
processes, a synchronization protocol must be setup.
46
A shared memory segment is identified by a unique integer, the shared memory ID. The shared
memory itself is described by a structure of type shmid_ds in header file sys/shm.h. To use this
file, files sys/types.h and sys/ipc.h must be included.
WRITER PROCESS
ALGORITHM:
2. If allowed i.e. wait() gives a true value, it enters and performs the write. If not allowed, it keeps
on waiting.
do {
while(true);
Program:
#include <stdio.h>
int main()
47
// shmat to attach to shared memory
gets(str);
shmdt(str);
return 0;
2)If allowed:
2.1) it increments the count of number of readers inside the critical section. If this reader is the first
reader entering, it locks the wrt semaphore to restrict the entry of writers if any reader is inside.
2.2)It then, signals mutex as any other reader is allowed to enter while others are already reading.
2.3) After performing reading, it exits the critical section. When exiting, it checks if no more
reader is inside, it signals the semaphore wrt as now, writer can enter the critical section.
do {
wait(mutex);
// that is, no reader is left in the critical section, if (readcnt == 0) signal(wrt); // writers can
enter signal(mutex);
49
PROGRAM:
#include <stdio.h>
int main()
shmdt(str);
shmctl(shmid,IPC_RMID,NULL);
return 0;
50
EXECUTION & OUTPUT:
51
Result : To write a C program to implement inter process communication was implemented successfully.
Algorithm
Program
Output
Viva
52
Ex.No: 5 IMPLEMENTATION OF DEADLOCK - BANKERS ALGORITHM
AIM:
To write a UNIX C Program for the Implementation of Banker's
PROBLEM DESCRIPTION:
The Banker’s Algorithm was designed and developed by a Dutch Computer Scientist,
Edsger Djikstra. The Banker’s Algorithm is a Resource Allocation and a Deadlock Avoidance
Algorithm.
This algorithm takes analogy of an actual bank where clients request to withdraw cash. The
Banking Authorities have some data according to which the cash is lent to the client. The Banker
cannot give more cash than the client’s request and the total cash available in the bank.
1. Safety Test Algorithm: This algorithm checks the current state of the system to maintain its
Safe State.
2. Resource Request Handling Algorithm: This algorithm verifies if the requested resources,
after their allocation to the processes affects the Safe State of the System. If it does, then the
request of the process for the resource is denied, thereby maintaining the Safe State.
53
A State is considered to be Safe if it is possible for all the Processes to Complete its Execution
without causing any Deadlocks. An Unsafe State is the one in which the Processes cannot
complete its execution.
ALGORITHM:
Step-3: Read the number of process, resources, allocation matrix and available matrix.
Step-4: Compare each and every process using the banker‟s algorithm.
Step-5: If the process is in safe state then it is a not a deadlock process otherwise it is a
deadlock process
PROGRAM:
#include <stdio.h>
int main()
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
54
{ 0, 0, 2 } }; // P4
{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4
f[k] = 0;
int need[n][m];
int y = 0;
if (f[i] == 0) {
int flag = 0;
flag = 1;
55
break;
}}
if (flag == 0) {
ans[ind++] = i;
avail[y] += alloc[i][y];
f[i] = 1;
}}}}
return (0);
Algorithm
Program
Output
Viva
56
Ex. No.:6 PAGE REPLACEMENT ALGORITHMS
AIM:
To write a program in C to implement page replacement algorithm FIFO
PROBLEM DESCRIPTION:
Page replacement algorithms are used to decide what pages to page out when a page needs
to be allocated. This happens when a page fault occurs and free page cannot be used to satisfy
allocation
LRU:
“Replace the page that had not been used for a longer sequence of time”. The frames are
empty in the beginning and initially no page fault occurs so it is set to zero. When a page fault
occurs the page reference sting is brought into the memory. The operating system keeps track of all
pages in the memory, thereby keeping track of the page that had not been used for longer sequence
of time. If the page in the page reference string is not in memory, the page fault is incremented and
the page that had not been used for a longer sequence of time is replaced. If the page in the page
reference string is in the memory take the next page without calculating the next page. 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 pages are referred and calculate the page fault for all those pages in the
page references string for the number of available frames.
Algorithm
● Declare the size.
● Get the number of pages to be inserted.
● Get the value.
● Declare counter and stack.
● Select the least recently used page by counter value.
● Stack them according the selection.
● Display the values.
57
● Stop the process
Program
#include<stdio.h>
int findLRU(int time[], int n){
minimum = time[i];
pos = i;
}
}
return pos;
}
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i, j,
pos, faults = 0;
}
58
for(i = 0; i < no_of_pages; ++i){
flag1 = flag2 = 0;
flag1 = flag2 = 1;
break;
}
}
if(flag1 == 0){
for(j=0;j<no_of_frames;++j){
if(frames[j]==-1){
counter++;
faults++;
frames[j] = pages[i];
time[j] = counter;
flag2 = 1;
break;
}}}
if(flag2 == 0){
pos = findLRU(time, no_of_frames);
counter++;
faults++;
frames[pos] = pages[i];
time[pos] = counter;
}
59
printf("\n");
for(j = 0; j < no_of_frames; ++j){
printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);
return 0;
}
EXECUTION & OUTPUT:
60
AIM : : To write c program to implement Optimal replacement algorithm
ALGORITHM:
1. Read The Number Of Pages, Reference String, Cache Size
2. Let Cache Size Be N. Add First N Elements From Reference String To Cache Directly. Print Cache And
Increment Page Faults.
3. For The Elememts Left Do The Following..
3.1 There May Be 2 Cases. Either The Element In The Reference String May Be In The Cache Already. Or It
Is Not Present
3.2 If The Element Is Not In The Cache Do The Following(Uses The Function Ispresent() To Check If The
Element Is Present Or Not)
3.2.1 For All The Elements In The Cache Find Respective Length From Current Index In The Reference
String (Using Findlength() Function)
3.2.2 Find The Maximum Of The Lengths (Using Findmax() Function )
3.2.3 Replace That Index Of Cache With The Element Of Reference String
3.2.4 Increment Page Fault
3.3 Else Do Nothing
4. Print Page Faults
PROGRAM:
#include <stdio.h>
int main()
{
//variable declaration and initialization
int frames_number, pages_number, frames[10],faults, pages[30], temp[10], flag1, flag2, flag3, i, j,
k, pos, max, miss = 0;
61
for(i = 0; i < pages_number; ++i){
scanf("%d", &pages[i]);
}
}
}
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}
// definition of the flag at the mid position
62
if(flag2 == 0){
flag3 =0;
for(j = 0; j < frames_number; ++j){
temp[j] = -1;
}
}
63
frames[pos] = pages[i];
miss++;
}
printf("\n");
for(j = 0; j < frames_number; ++j){
printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page miss = %d", miss);
return 0;
}
EXECUTION & OUTPUT:
64
AIM : To write c program to implement FIFO algorithm
ALGORITHM:
4. Check the need of replacement from old page to new page in memory
5. Forma queue to hold all pages
6. Insert the page require memory into the queue
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
65
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++){
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
return 0;
66
Result : Thus c program to implement FIFO algorithm was implemented successfully.
Algorithm
Program
Output
Viva
67
MEMORY MANAGEMENT FUNCTIONS
ALGORITHM:
int main()
{
int fragments[10], block[10], file[10], m, n, number_of_blocks, number_of_files, temp, lowest
= 10000;
static int block_arr[10], file_arr[10];
printf("\nEnter the Total Number of Blocks:\t");
scanf("%d", &number_of_blocks);
printf("\nEnter the Total Number of Files:\t");
scanf("%d", &number_of_files);
printf("\nEnter the Size of the Blocks:\n");
for(m = 0; m < number_of_blocks; m++)
{
68
printf("Block No.[%d]:\t", m + 1);
scanf("%d", &block[m]);
}
{
if(block_arr[n] != 1)
{
temp = block[n] - file[m];
if(temp >= 0)
{
if(lowest > temp)
{
file_arr[m] = n;
lowest = temp;
}
}
}
fragments[m] = lowest;
block_arr[file_arr[m]] = 1;
lowest = 10000;
69
}
}
printf("\nFile Number\tFile Size\tBlock Number\tBlock Size\tFragment");
for(m = 0; m < number_of_files && file_arr[m] != 0; m++)
{
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", m, file[m], file_arr[m], block[file_arr[m]],
fragments[m]);
}
printf("\n");
return 0;
}
70
Result : Thus c program to implement best fit was executed successfully.
Algorithm
Program
Output
Viva
71
Ex. No. 7b Memory Management Scheme using First Fit.
AIM:
To write a C program to implement the memory management scheme using first fit
ALGORITHM:
1. Get no. of Processes and no. of blocks.
2. After that get the size of each block and process requests.
3.Now allocate processes
if(block size >= process size)
4. Display the processes with the blocks that are allocated to a respective process.
5.Stop.
PROGRAM:
#include<stdio.h>
int main()
{
72
printf("Block No.[%d]:\t", m + 1);
scanf("%d", &blocks[m]);
}
{
if(block_arr[n] != 1)
{
temp = blocks[n] - files[m];
if(temp >= 0)
{
file_arr[m] = n;
break;
}
}
}
fragments[m] = temp;
block_arr[file_arr[m]] = 1;
}
printf("\nFile Number\tBlock Number\tFile Size\tBlock Size\tFragment");
for(m = 0; m < number_of_files; m++)
73
{
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", m, file_arr[m], files[m], blocks[file_arr[m]],
fragments[m]);
printf("\n");
return 0;
}
74
Result : Thus c program to implement best fit was implemented successfully.
Algorithm
Program
Output
Viva
75
Ex. No. 7c Memory Management Scheme using Worst Fit.
AIM:
To write a C program to implement the memory management scheme using worst fit.
Exercise:
Given memory partition of 100 KB, 500 KB, 200 KB, 300 KB and 600 KB (in order), how would
each of the first-fit, best fit and worst fit algorithms place processes of 212 KB, 417 KB, 112 KB
and 426 KB (in order)? Which algorithm makes the most efficient use of memory? Either it is
worst fit.
ALGORITHM:
Step 1:Input memory block with a size.
Step 2:Input process with size.
Step 3:Initialize by selecting each process to find the maximum block size that can be assigned to
the current process.
Step 4:If the condition does not fulfill, they leave the process.
Step 5:If the condition is not fulfilled, then leave the process and check for the next process.
Step 6:Stop.
PROGRAM:
#include<stdio.h>
int main()
{
int fragments[10], blocks[10], files[10];
scanf("%d", &blocks[m]);
}
printf("Enter the Size of the Files:\n");
for(m = 0; m < number_of_files; m++)
{
printf("File No.[%d]:\t", m + 1);
scanf("%d", &files[m]);
}
for(m = 0; m < number_of_files; m++)
{
for(n = 0; n < number_of_blocks; n++)
{
if(block_arr[n] != 1)
{
temp = blocks[n] - files[m];
if(temp >= 0)
{
if(top < temp)
{
file_arr[m] = n;
top = temp;
}
}
}
fragments[m] = top;
77
block_arr[file_arr[m]] = 1;
top = 0;
}
}
printf("\nFile Number\tFile Size\tBlock Number\tBlock Size\tFragment");
for(m = 0; m < number_of_files; m++)
{
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", m, files[m], file_arr[m], blocks[file_arr[m]],
fragments[m]);
}
printf("\n");
return 0;
}
78
Result : Thus c program for worst fit was executed successfully
Algorithm
Program
Output
Viva
79
Ex No: 8 IMPLEMENTATION OF DISK SCHEDULING ALGORITHMS
AIM:
To write a ‘C’ program to implement the Disk Scheduling algorithm for First Come First
Served (FCFS), Shortest Seek Time First (SSTF), and SCAN.
PROBLEM DESCRIPTION:
Disk Scheduling is the process of deciding which of the cylinder request is in the ready
queue is to be accessed next.
The access time and the bandwidth can be improved by scheduling the servicing of disk
I/O requests in good order.
Access Time:
The access time has two major components: Seek time and Rotational Latency.
Seek Time:
Seek time is the time for disk arm to move the heads to the cylinder containing the
desired sector.
Rotational Latency:
Rotational latency is the additional time waiting for the disk to rotate the desired sector to
the disk head.
Bandwidth:
The disk bandwidth is the total number of bytes transferred, divided by the total time
between the first request for service and the completion of the last transfer.
PROCEDURE:
1. Input the maximum number of cylinders and work queue and its head starting position.
2. First Come First Serve Scheduling (FCFS) algorithm – The operations are performed in
order requested
7. Since seek time increases with the number of cylinders traversed by the head, SSTF chooses
the pending request closest to the current head position.
9. SCAN Scheduling algorithm –The disk arm starts at one end of the disk, and moves toward
the other end, servicing requests as it reaches each cylinder, until it gets to the other end of the
disk.
10. At the other end, the direction of head movement is reversed and servicing continues.
11. The head continuously scans back and forth across the disk.
AIM: To write a C program to implement the Disk Scheduling algorithm for First Come First
Served (FCFS), Shortest Seek Time First (SSTF), and SCAN.
ALGORITHM:
1. Let
Request array represents an array storing indexes of tracks that have been requested in
ascending order of their time of arrival. head is the position of disk head.
2. Let
us one by one take the tracks in default order and calculate the absolute distance of the track
from the head.
4. Currently serviced track position now becomes the new head position.
5.Go to step 2 until all tracks in request array have not been serviced.
Program :
#include<stdio.h>
int main()
int queue[20],n,head,i,j,k,seek=0,max,diff;
float avg;
81
printf("Enter the max range of disk:");
scanf("%d",&max);
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&queue[i]);
scanf("%d",&head);
queue[0]=head;
for(j=0;j<=n-1;j++)
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
avg=seek/(float)n;
return 0;
82
SSTF:
ALORITHM:
1. LetRequest array represents an array storing indexes of tracks that have been requested. head is
the position of disk head.
2. Find the positive distance of all tracks in the request array from head.
3. Find a track
from requested array which has not been accessed/serviced yet and has minimum
distance from head.
5. Currently serviced track position now becomes the new head position.
6.Go to step 2 until all tracks in request array have not been serviced
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
int queue[100],t[100],head,seek=0,n,i,j,temp;
float avg;
83
// clrscr();
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&queue[i]);
scanf("%d",&head);
for(i=1;i<n;i++)
t[i]=abs(head-queue[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(t[i]>t[j])
temp=t[i];
t[i]=t[j];
t[j]=temp;
temp=queue[i];
queue[i]=queue[j];
queue[j]=temp;
}
84
}
for(i=1;i<n-1;i++)
seek=seek+abs(head-queue[i]);
head=queue[i];
avg=seek/(float)n;
return 0;
SCAN:
ALGORITHM:
1. Let
Request array represents an array storing indexes of tracks that have been requested in
ascending order of their time of arrival. head is the position of disk head.
2. Let direction represents whether the head is moving towards left or right.
3.In the direction in which head is moving service all tracks one by one.
6. Currently serviced track position now becomes the new head position.
85
7,Go to step 3 until we reach at one of the ends of the disk.
If we reach at the end of the disk reverse the direction and go to step 2 until all tracks in request
array have not been serviced.
PROGRAM:
#include<stdio.h>
#include<math.h>
int main()
int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],
temp1=0,temp2=0;
float avg;
scanf("%d",&max);
scanf("%d",&head);
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&temp);
if(temp>=head)
queue1[temp1]=temp;
temp1++;
86
}
else
queue2[temp2]=temp;
temp2++;
for(i=0;i<temp1-1;i++)
for(j=i+1;j<temp1;j++)
if(queue1[i]>queue1[j])
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
for(i=0;i<temp2-1;i++)
for(j=i+1;j<temp2;j++)
if(queue2[i]<queue2[j])
{
87
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];
queue[i]=max;
for(i=temp1+2,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[i]=0;
queue[0]=head;
for(j=0;j<=n+1;j++)
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
avg=seek/(float)n;
return 0;
88
EXECUTION & OUTPUT:
Algorithm
Program
Output
Viva
89
Ex No: 9 IMPLEMENTATION OF ACCESS CONTROL MECHANISM
AIM:
Access control is the traditional center of gravity of computer security. It is where security
engineering meets computer science. Its function is to control which principals (persons, processes,
machines, . . .) have access to which resources in the system—which files they can read, which
programs they can execute, how they share data with other principals, and so on.
The access control mechanisms, which the user sees at the application level, may express a
very rich and complex security policy. A modern online business could assign staff to one of
dozens of different roles, each of which could initiate some subset of several hundred possible
transactions in the system. Some of these (such as credit card transactions with customers) might
require online authorization from a third party while others (such as refunds) might require dual
control.The applications may be written on top of middleware, such as a database management
system or bookkeeping package, which enforces a number of protection properties. For example,
bookkeeping software may ensure that a transaction that debits one ledger for a certain amount
must credit another ledger for the same amount
The middleware will use facilities provided by the underlying operating system. As this constructs
resources such as files and communications ports from lower-level components, it acquires the
responsibility for providing ways to control access to them.
Finally, the operating system access controls will usually rely on hardware features provided by
the processor or by associated memory management hardware. These control which memory
addresses a given process can access
90
etc) to mark the permissions applied to the object. In the same way, there is an owner/user and a
set of options that can be shared (groups, other users…).
91
- usuario2 can read but not modify usuario1’s fichero1 because of the assigned permissions -
Mandatory Access Control, MAC: This access mechanism is a compliment of the previous ones
and adds another safety layer for access and privilege control. MAC bases itself on “tagging”
every element in the system that will then undergo the access control policies that have been
configured. Therefore, in any operation by a subject on an object the tags will be verified and the
established MAC policies will be applied to determine if the operation is allowed, even when it has
complied with other security controls. In contrast with the discretionary access control, the user
can modify permissions and tags but can’t fix access controls that suppose a violation of the
92
system’s MAC policies. It’s the responsibility of a privileged user to establish the MAC’s central
policies that will govern the controls to be applied depending on the established tags. Examples of
these control methods are SELinux in Linux/Redhat/Centos/Fedora distributions or AppArmor in
Linux SuSE.
.
93
Viva-Voce questions:
Algorithm
Program
Output
Viva
Total
Result
94
Ex No: 10 IMPLEMENTATION OF CRYPTOGRAPHIC ALGORITHMS
AIM:
To write a ‘C’ program to implement various Cryptography Algorithms such as RSA, DEA,
Blowfish.
Definition
In cryptography, encryption is the process of encoding a message or information
in a way that only authorized parties can access it and those who are not
authorized cannot.
Asymmetric Encryption
In public-key encryption schemes, the encryption key is published for anyone to
use and for encrypting messages. Only the receiving party has access to the
decryption key that enables messages to be read. Public-key encryption was first
described in a secret document in 1973. Before that, all encryption schemes
were symmetric-key (also called private-key).
95
Symmetric Encryption
In symmetric-key schemes, the encryption and decryption keys are the same.
Communicating parties must have the same key in order to achieve secure
communication.
Encryption Algorithms
Triple DES
Triple DES was designed to replace the original Data Encryption Standard (DES)
algorithm, which hackers learned to defeat with ease. At one time, Triple DES
was the recommended standard and the most widely used symmetric algorithm
in the industry. Triple DES uses three individual keys with 56 bits each. The
total key length adds up to 168 bits, but experts say that 112-bits in key
strength is more like it.Though it is slowly being phased out, Triple DES is still a
dependable hardware encryption solution for financial services and other
industries.
RSA
RSA is a public-key encryption algorithm and the standard for encrypting data
sent over the internet. It also happens to be one of the methods used in PGP and
GPG programs. Unlike Triple DES, RSA is considered an asymmetric encryption
algorithm because it uses a pair of keys. The public key is used to encrypt a
message and a private key to decrypt it. It takes attackers quite a bit of time and
processing power to break this encryption code.
AES
The Advanced Encryption Standard (AES) is the algorithm trusted as the
standard by the U.S. government and many other organizations. Although it is
extremely efficient in 128-bit form, AES also uses keys of 192 and 256 bits for
heavy-duty encryption. AES is considered resistant to all attacks, with the
exception of brute-force attacks, which attempt to decipher messages using all
possible combinations in the 128-, 192- or 256-bit cipher. Still, security experts
believe that AES will eventually become the standard for encrypting data in the
private sector.
96
Encryption Standards
There are a number of standards related to cryptography. Here are the following
standards for encryption:
• Data Encryption Standard (now obsolete)
• Advanced Encryption Standard
• RSA (the original public-key algorithm)
• Open PGP
97
Encryption Best Practices
1. Know the laws: When it comes to safeguarding the personally identifiable
information, organizations must adhere to many overlapping, privacy-
related regulations. The top six regulations that impact many
organizations include: FERPA, HIPAA, HITECH, COPPA, PCI DSS
and state-specific data breach notifications laws.
2. Assess the data: A security rule under HIPAA does not explicitly require
encryption, but it does state that entities should perform a data risk
assessment and implement encryption if the evaluation indicates that
encryption would be a “reasonable and appropriate” safeguard. If an
organization decides not to encrypt electronic protected health information
(ePHI), the institution must document and justify that decision and then
implement an “equivalent alternative measure.”
3. Determine the required or needed level of encryption: The U.S.
Department of Health and Human Services (HHS) turns to the National
Institute of Standards and Technology (NIST) for recommended encryption-
level practices. HHS and NIST have both produced robust documentation
for adhering to HIPAA’s Security Rule. NIST Special Publication 800-
111 takes a broad approach to encryption on user devices. In a nutshell, it
states that when there is even a remote possibility of risk, encryption
needs to be in place. FIPS 140-2, which incorporates AES into its protocols,
is an ideal choice. FIPS 140-2 helps education entities ensure that PII is
“rendered unusable, unreadable or indecipherable to unauthorized
individuals.” A device that meets FIPS 140-2 requirements has a
cryptographic erase function that “leverages the encryption of target data
by enabling sanitization of the target data’s encryption key, leaving only
the cipher text remaining on the media, effectively sanitizing the data.”
4. Be mindful of sensitive data transfers and remote access: Encryption
must extend beyond laptops and backup drives. Communicating or
sending data over the internet needs Transport Layer Security (TLS), a
protocol for transmitting data over a network, and AES encryption. When
an employee accesses an institution’s local network, a secure VPN
98
connection is essential when ePHI is involved. Also, before putting a
handful of student files on a physical external device for transfer between
systems or offices, the device must be encrypted and meet FIPS 140-2
requirements to avoid potential violations.
5. Note the fine print details: Unfortunately, many schools fail to engage in
proper due diligence in reviewing third-party services’ privacy and data-
security policies, and inadvertently authorize data collection and data-
mining practices that parents/students find unacceptable or violate
FERPA. Regulatory compliance entails much more than simply password-
protecting an office’s workstations. It requires using encryption to protect
data-at-rest when stored on school systems or removable media device.
Remember that data at rest that is outside the school’s firewall (or “in the
wild”) is the top source of security breaches.
Aim :
Algorithm:
RSA involves use of public and private key for its operation. The keys are generated using the
following steps:-
4. Choose e such that e > 1 and coprime to totient which means gcd (e, totient) must be equal
to 1, e is the public key
5. Choose d such that it satisfies the equation de = 1 + k (totient), d is the private key not known to
everyone.
6. Cipher text is calculated using the equation c = m^e mod n where m is the message.
7. With the help of c and d we decrypt message using equation m = c^d mod n where d is the
private key.
Program :
99
#include<stdio.h>
#include<math.h>
int temp;
while(1)
temp = a%h;
if(temp==0)
return h;
a = h;
h = temp;
int main()
double p = 3;
double q = 7;
double n=p*q;
double count;
100
//public key
double e=2;
while(e<totient){
count = gcd(e,totient);
if(count==1)
break;
else
e++;
//private key
double d;
double k = 2;
d = (1 + (k*totient))/e;
double c = pow(msg,e);
double m = pow(c,d);
c=fmod(c,n);
101
m=fmod(m,n);
printf("\np = %lf",p);
printf("\nq = %lf",q);
printf("\nn = pq = %lf",n);
printf("\ntotient = %lf",totient);
printf("\ne = %lf",e);
printf("\nd = %lf",d);
return 0;
OUTPUT :
DES ALGORITHM
The DES algorithm is also sometimes referred to as Data Encryption Algorithm (DEA). The DES
encryption algorithm is a symmetric key algorithm for the encryption of data. The block size is of
64 bits.
The DES is an archetypal block cipher which takes a fixed length string of plain-text bits. There’s
another improvised version of this algorithm which is Triple DES Algorithm.
102
The simplified DES (S-DES) is a modified version of the data encryption standard DES algorithm.
Another modified version of the DES algorithm is famously known as Triple DES. The key
generator method creates 16 48-bit keys
PROGRAM:
#include<stdio.h>
int main()
scanf("%d", &plaintext);
scanf("%d", &key);
scanf("%d", &array_a1[count]);
div = plaintext / 2;
array_a3[count] = 0;
dec++;
dec = dec - 1;
103
printf("Enter the Key Bit Stream\n");
scanf("%d", &array_a3[dec++]);
printf("%d", array_a8[count]);
printf("Left Hand\n");
array_a5[count] = array_a1[count];
printf("%d", array_a1[count]);
printf("Right Hand\n");
array_a2[count] = array_a1[count];
printf("%d", array_a1[count]);
array_a6[j] = 0;
104
}
array_a6[j] = m;
else
array_a6[j] = 0;
printf("\nFirst XOR\n");
printf("%d", array_a6[count]);
array_a4[j] = 0;
array_a4[j] = m;
array_a4[j] = 0;
printf("\nSecond XOR\n");
printf("%d", array_a4[j]);
return 0;
106
Viva-Voce questions:
1. What is cryptography?
2. What exactly are encryption and decryption?
3. What is plaintext or cleartext?
4. What is ciphertext?
5. How does the encryption process actually take place?
6. What are the origins of cryptography?
7. What is the Caesar cipher?
8. What is the goal of cryptography?
Algorithm
Program
Output
Viva
Total
Result :
To write a ‘C’ program to implement various Cryptography Algorithms such as RSA, DEA,
Blowfish was implemented successfully.
107
108