0% found this document useful (0 votes)
7 views105 pages

OS - Lab Manual - For Ref in Artificial Intelligence

OS - Lab Manual - for ref in artificial intelligence and machine learning with python program and certificate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views105 pages

OS - Lab Manual - For Ref in Artificial Intelligence

OS - Lab Manual - for ref in artificial intelligence and machine learning with python program and certificate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Department of Computer Science and Engineering

OPERATINGSYSTEM
Lab Manual(212CSE3303)

Student Name :

Register Number :

Section :

1
TABLEOFCONTENTS

S.No Topic PageNo.

1 Bonafide Certificate

2 Experiment Evaluation Summary

3 Course Plan

4 Introduction

Experiments

5 Study of basic Commands in Windows & Unix Operating


System
6 Simulation of System calls

7 Implementation of CPU scheduling algorithms

8 Simulation of IPC in UNIX

9 Implementation of dead lock avoidance algorithms

10 Implementation of Page replacement algorithms

11 Implementation of memory management functions

12 Implementation of disk scheduling algorithms

13 Implementation of access control mechanisms

Implementation of encryption algorithms


14

2
DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING

BONAFIDECERTIFICATE

Bonafide record of work done by

of in OPERATING SYSTEMS (212CSE3303) during even/odd

semester in academic year

Staff In-charge Head of the Department

SubmittedtothepracticalExaminationheldatKalasalingamAcademyofResearchandEducation,

Anand nagar, Krishnankoil on

REGISTERNUMBER

Internal Examiner External Examiner


3
EXPERIMENTEVALUATIONSUMMARY

Name: Reg No:

Class: Faculty name:

Marks
S.No Name of the Experiment Date Faculty Signature
(100)
1 Study of basic Commands in windows
and Linux Operating System

2 Write programs using the following


system calls (fork, exec, getpid, exit,
wait, close, stat, opendir, readdir).
Write programs using the I/O system
calls (open, read, write, etc).
3 Write a program to implementation
CPU Scheduling Algorithms (FCFS,
SJF,RR, and Priority).
Write a C program to Simulate Multi-
level queue Scheduling Algorithm

4 Simulation of IPC in UNIX

5 Implementation of deadlock avoidance


– banker’s algorithms.
6 Implementation of Page replacement
algorithms. Write a C program to
simulate Optimal Page Replacement
Algorithm
7 Implementation of memory allocation
algorithms(First Fit ,Best Fit,Worst Fit)

8 Implementation of Disk Scheduling


Algorithms.
9 Implementation of Access Control

10 Implementation of Cryptographic
Algorithms

4
BASICLINUXCOMMANDS

EX. NO. 1a WORKING WITH FILES AND DIRECTORIES

AIM:

To study the UNIX commands for accessing files and directories.

COMMANDSDESCRIPTION:

 cat — Create and display short files.


 chmod — Change file permissions.
 cd — Change directory.
 cp — Copy files.
 date — Display the current date and time.
 echo — Display a line of text or a variable value.
 ftp — Connect to a remote machine to download or upload files.
 grep — Search for a pattern in a file.
 head — Display the first part of a file.
 ls — List files and directories.
 lpr — Standard print command.
 more — View the contents of a file one screen at a time.
 mkdir — Create a new directory
 mv — Move or rename files
 ncftp — Enhanced FTP client, especially good for downloading via anonymous FTP
 print — Custom print command (may be user-defined or system-specific)
 pwd — Show the current working directory
 rm — Remove a file
 rmdir — Remove a directory
 rsh — Remote shell to execute commands on another machine
 setenv — Set an environment variable (used in C shell)
 sort — Sort the contents of a file
 tail — Display the last part of a file
 tar — Create or extract archive files
 telnet — Log into another machine remotely
 wc — Count characters, words, and lines in a file

5
EXECUTION&OUTPUT:

6
7
Result: The general purpose utility commands was executed successfully.

Assessment of an Individual experiment

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.

COMMANDSDESCRIPTION:
 bc — An arbitrary precision calculator language.
 cal — Display a calendar
 date — Print or set the system date and time
 echo — Display a line of text
 expr — Evaluate expressions
 factor — Factor numbers
 passwd — Update a user's authentication tokens
 printf — Format and print data
 rev — Reverse lines of a file or files
 seq — Print a sequence of numbers
 test — Check file types and compare values
 uname — Print system information
 w — Show who is logged on and what they are doing
 who — Show who is logged on
 whoami — Show the current user

9
EXECUTION&OUTPUT:

10
Result: The general purpose utility commands was executed successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

11
SYSTEMCALLS
Ex.No.2a Fork System Call

AIM:

To write a program to create a child process using the system call fork().

ALGORITHM:

1. Call fork() to create a child process.


o fork() returns:
 0 → Parent process (value is child’s PID)
 = 0 → Child process
 < 0 → Error in creating child process
2. Print PID (Process ID) and PPID (Parent Process ID) from both parent and child processes.
3. In the parent process, use wait(NULL) to wait for the child to complete.
4. In the child process, use exit(0) to terminate the process.

PROGRAM:

#include <stdio.h>
#include
<stdlib.h>#include<sy
s/types.h>#include
<sys/wait.h>
#include<unistd.h> int
main(void) {
pid_tpid=fork();
if(pid == 0) {

printf("Child=>PPID:%dPID:%d\n",getppid(),getpid());
exit(EXIT_SUCCESS);

}
elseif(pid>0) {

12
printf("Parent => PID: %d\n", getpid());
printf("Waitingforchildprocesstofinish.\n");
wait(NULL);
printf("Childprocess finished.\n");
}
else{

printf("Unableto createchildprocess.\n");
}

returnEXIT_SUCCESS;
}

EXECUTION&OUTPUT:

13
Result: Hence create a child process using the system calls–fork executed successfully

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

14
Ex.No.2b EXEC System Call

AIM:

To write a program to display the current date and time using the exec system call.

ALGORITHM:

1. The exec system call replaces the current process image with a new process image.
2. The new process image is specified as an argument to the exec function (e.g., date command).
3. The currently running process does not continue after exec; it gets replaced.
4. The new process retains the same PID, environment, and file descriptors.
5. The virtual memory and process image are replaced with those of the new program.
6. Use execlp("date", "date", NULL) to run the Linux date command using the system PATH.

PROGRAM:
#include <stdio.h>
#include<unistd.h>
#include <stdlib.h>

intmain(intargc,char*argv[])
{
printf("PIDofexample.c=%d\n",getpid());
char*args[]={"Hello","C","Programming",NULL};
execlp("date","date", NULL);
execv("./hello", args);
printf("Backtoexample.c"); return
0;
}

15
Result: Thus to display time and date using exec system call was executed successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

16
Ex.No. 2c STAT System Call

AIM:

To write a program to implement the stat() system call to retrieve file attributes such as inode number, size,
access/modification/change times, etc.

DESCRIPTION:

The stat() system call retrieves information about a file and fills a structure of type struct stat with the file’s
metadata.

 atime – Time of last access (ls -lu)


 mtime – Time of last modification (ls -l)
 ctime – Time of last status change (ls -lc)

ALGORITHM:

1. Include necessary headers.


2. Declare a struct stat variable to hold file information.
3. Use stat() function and pass the filename and address of the stat structure.
4. If stat() returns 0, print:
o Inode number
o File size
o User ID and Group ID
o Last access, modification, and change times
5. If stat() fails, display an error using perror()

PROGRAM:

#include<sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
intmain(intargc,char*argv[]){ struct
stat sb;
if(argc!=2){

fprintf(stderr,"Usage:%s<pathname>\n",argv[0]);

exit(EXIT_FAILURE);

17
}

if(stat(argv[1],&sb)==-1){
perror("stat");
exit(EXIT_FAILURE);

printf("Filetype: ");

switch(sb.st_mode&S_IFMT){

case S_IFBLK:printf("block device\n"); break;


case S_IFCHR:printf("character device\n"); break;
case S_IFDIR:printf("directory\n"); break;
case S_IFIFO:printf("FIFO/pipe\n"); break;
case S_IFLNK:printf("symlink\n"); break;
case S_IFREG:printf("regular file\n"); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}

printf("I-nodenumber: %ld\n",(long)sb.st_ino);

printf("Mode: %lo(octal)\n",
(unsigned long) sb.st_mode);

printf("Link count: %ld\n",(long)sb.st_nlink);


printf("Ownership: UID=%ldGID=%ld\n",
(long)sb.st_uid,(long)sb.st_gid);

18
printf("PreferredI/Oblocksize:%ldbytes\n",
(long) sb.st_blksize);

printf("File size: %lldbytes\n",

(long long) sb.st_size);


printf("Blocks allocated: %lld\n",
(long long) sb.st_blocks);

printf("Last status change: %s", ctime(&sb.st_ctime));


printf("Last file access: %s", ctime(&sb.st_atime));
printf("Lastfilemodification:%s",ctime(&sb.st_mtime));

exit(EXIT_SUCCESS);

EXECUTION&OUTPUT:

19
Result: Thus program to implement STAT system call was implemented successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

20
Ex.No. 2d wait() System Call

AIM:

To write a program using the wait() system call to ensure the parent process waits for the child process to
complete before continuing.

DESCRIPTION:

The wait() system call is used in a parent process to wait until any of its child processes terminates. This
helps in:

 Synchronizing execution
 Cleaning up zombie processes (terminated child processes not yet reaped)

There are two outcomes when wait() is called:

1. If child processes are running → the parent blocks until any child exits.
2. If no child process exists → wait() returns immediately.

ALGORITHM:

1. Print a message before fork().


2. Use fork() to create a child process.
3. In the child process:
o Print its process ID and parent ID.
o Simulate work using sleep().
o Exit the child process using exit(0).
4. In the parent process:
o Call wait(NULL) to block until the child finishes.
o Then print messages from the parent process.

PROGRAM:
#include<unistd.h>#in
clude<sys/types.h>#inc
lude<stdio.h>

21
#include<sys/wait.h>i
nt main()
{
pid_tp;
printf("before fork\n");
p=fork();
if(p==0)//child
{
printf("Iamchildhavingid%d\n",getpid());
printf("My parent's id is %d\n",getppid());

}
else//parent

{
wait(NULL);
printf("Mychild'sidis%d\n",p);
printf("Iamparenthavingid%d\n",getpid());
}
printf("Common\n");

22
EXECUTION&OUTPUT:

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

Result: Thus program using wait system call was executed successfully

23
Ex.No. 2e Input/Output System Call

AIM:

To write a program to implement the concept of I/O system calls such as creat(), open(), read(), write(),
close(), and unlink().

DESCRIPTION:

This experiment demonstrates low-level file I/O system calls used in Unix/Linux:

 creat() – Creates a new file with specified permissions.


 open() – Opens an existing file or creates one (with flags).
 read() – Reads data from a file.
 write() – Writes data into a file.
 lseek() – Moves the file pointer to a desired position.
 close() – Closes an opened file.
 unlink() – Deletes the file.

ALGORITHM:

1. Use creat() or open() with O_CREAT to create a file.


2. Write a string to the file using write().
3. Use lseek() to move the file pointer to the beginning.
4. Read the data back using read().
5. Print the data read from the file.
6. Close the file using close().
7. Optionally, delete the file using unlink().

PROGRAM:
//Cprogramtoillustrate
//opensystemcall
#include<stdio.h>

#include<fcntl.h>
#include<errno.h>

extern int errno;


int main()
{
//iffiledoesnot haveindirectory
//thenfilefoo.txt iscreated.

24
intfd=open("foo.txt",O_RDONLY|O_CREAT); int
close(int fd);
printf("fd=%d/n",fd);

if(fd ==-1)

{
//print whichtypeoferrorhaveinacode
printf("Error Number % d\n", errno);

//printprogramdetail"Successorfailure"perror("Program");

}
return 0;

EXECUTION&OUTPUT:

25
Result: Thus program to implement the concept of I/O call was executed successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

26
Ex.No. 3a First Come First Serve (FCFS) Scheduling Algorithm

AIM:

To write a program using C in a UNIX environment to implement the First Come First Serve (FCFS) CPU
scheduling algorithm.

ALGORITHM:

1. Create the number of processes.


2. Get the Process ID and Service Time (Burst Time) for each process.
3. Set Waiting Time of the first process to 0.
4. Total Time (Turnaround Time) of the first process = Service Time of that process.
5. For remaining processes:
o Waiting Time = Total Time of the previous process
o Total Time = Waiting Time + Service Time
6. Compute Total Waiting Time by summing all individual waiting times.
7. Compute Total Turnaround Time by summing all individual total times.
8. Calculate Average Waiting Time = Total Waiting Time / Number of processes.
9. Calculate Average Turnaround Time = Total Turnaround Time / Number of processes.
10. Display all results in a tabular form.

PROGRAM:
#include<stdio.h>struc
t process
{
int id,wait,ser,tottime;
}p[20];

main()
{
inti,n,j,totalwait=0,totalser=0,avturn,avwait;
printf("Enter number of process:");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
printf("Enterprocess_id:");
scanf("%d",&p[i].id);
27
printf("Enterprocessservicetime:");
scanf("%d",&p[i].ser);
}
p[1].wait=0;
p[1].tottime=p[1].ser;
for(i=2;i<=n;i++)

{
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);
}
printf("average waiting time %d\n",avwait);
printf("averageturnaroundtime%d\n",avturn);
}

28
EXECUTION&OUTPUT:

Result: Thus the C program to implement CPU scheduling algorithm for first come first serve was
executed successfully

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

29
Ex.No. 3b Shortest Job First (SJF) Scheduling

AIM:

To write a program using C in the UNIX environment to implement the Shortest Job First (SJF) CPU
scheduling algorithm (non-preemptive).

ALGORITHM:

1. Get the number of processes.


2. Get the Process ID and Service Time (Burst Time) for each process.
3. Sort the processes in ascending order of their burst times.
4. Set the Waiting Time of the first (shortest) process to 0.
5. For each subsequent process:
o Waiting Time = Total Time of the previous process
o Total Time (Turnaround Time) = Waiting Time + Burst Time
6. Compute Total Waiting Time by summing all waiting times.
7. Compute Total Turnaround Time by summing all total times.
8. Calculate Average Waiting Time = Total Waiting Time / Number of processes.
9. Calculate Average Turnaround Time = Total Turnaround Time / Number of processes.
10. Display the result in a tabular format.

PROGRAM:
#include<stdio.h>struc
t ff
{
intpid,ser,wait;
}p[20];
structfftmp;
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++)

30
{

printf("enter process id");


scanf("%d",&p[i]);
printf("enterservicetime");
scanf("%d",&p[i].ser);p[i].wait=0;
}
for(i=0;i<n-1;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;
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;

printf("TOTAL WAITING TIME :%d\n",totwait);


printf("AVERAGE WAITING TIME : %d\n",avwait);
31
printf("TOTAL TURNAROUND TIME :%d\n",tturn);
printf("AVERAGE TURNAROUND TIME:%d\n",aturn);
}

EXECUTION&OUTPUT:

Result: Thus the C program to implement the CPU scheduling algorithm for shortest job
first was executed successfully.

32
Ex.No.3c Round Robin Scheduling

AIM:
To write a program using C in a UNIX environment to implement the Round Robin scheduling concept.

ALGORITHM:

Step 1: Start the program.


Step 2: Receive inputs from the user for process ID, burst time, and arrival time.
Step 3: Calculate the waiting time for all the process IDs.

 i) The waiting time for the first instance of a process is calculated as:
a[i].waittime = count + a[i].arrivaltime
 ii) The waiting time for the remaining instances of the process is calculated as:
o a) If the time quantum is greater than the remaining burst time, then:
a[i].waittime = count + tq
o b) Else if the time quantum is less than or equal to the remaining burst time, then:
a[i].waittime = count - remaining_burst_time

Step 4: Calculate the average waiting time and average turnaround time.
Step 5: Print the results from Step 4.

PROGRAM:
#include<stdio.h>
struct roundRobin
{
intpburst,pburst1,wtime,endtime,arrivt,boolean,flagcntl;charpname[5];
}a[5];
int n,tq;
void input();

void initialize();
void calculate();
void display_waittime();
int main()
{
input();
initialize();
33
calculate();

display_waittime();
//getch();

//return 0;
}
void input()
{

inti;
printf("EnterTotalno.ofprocesses\n");
scanf("%d",&n);

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

printf("Enter process name:");

scanf("%s",&a[i].pname);
printf("Enter process burst time:");
scanf("%d",&a[i].pburst);
printf("Enterprocessarrivaltime:");
scanf("%d",&a[i].arrivt);
}
printf("\nEnterthetimequantum/TimeSlice:");
scanf("%d",&tq);
}

void initialize()

{inti;

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

34
a[i].pburst1=a[i].pburst;
a[i].wtime=0;
a[i].endtime=0;
a[i].boolean=0;
a[i].flagcntl=0;
}
}

voidcalculate()

{
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))//calculatingwaitingtimeforfirsttime
{
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)

35
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);
}
elseif((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;

printf("%d%s|",count,a[i].pname);
a[i].pburst1=0;

j++;
}
elseif(j==n) flag=0;
}//endoffor loop
}//endofwhileloop

voiddisplay_waittime()
{
inti,tot=0,turn=0;

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

{
printf("\n\nWaitingtimeforProcess%sis%d",a[i].pname,a[i].wtime);
tot=tot+a[i].wtime;
turn=turn+a[i].endtime-a[i].arrivt;
}

printf("\n\n\tAverage waiting time=%f",(float)tot/(float)n);


printf("\n\tAverage turnaround time=%f\n",(float)turn/(float)n);
}

EXECUTION&OUTPUT:

Result: Thus the C program to simulate CPU scheduling algorithm for round robin was executed
successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

37
Ex.No.3d Priority Scheduling

AIM:
To implement the Priority Scheduling algorithm using C in the UNIX environment.

ALGORITHM:

Step 1: Inside the structure, declare the required variables (e.g., process ID, burst time, priority, waiting
time, turnaround time).

Step 2: Declare the variables i, j as integers, and initialize total_wtime and total_ttime to zero.

Step 3: Get the value of n (number of processes), assign p, and allocate memory if needed.

Step 4: Inside a for loop, get the burst time and priority values for each process.

Step 5: Initialize the waiting time (wtime) of the first process to zero.

Step 6: Sort the processes by comparing their priorities (e.g., if p[i].priority > p[j].priority then swap).

Step 7: Calculate the total of burst time and waiting time. Compute the turnaround time as:
turnaround time = waiting time + burst time

Step 8: Display the results and stop the program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
intet[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;
charpn[10][10],t[10];

//clrscr();
printf("Enterthenumberofprocess:");
scanf("%d",&n);
38
for(i=0;i<n; i++)
{
printf("Enterprocessname,arrivaltime,executiontime&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++)

39
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("\nAverageturnaroundtimeis:%f",ata);
getch();
}

40
EXECUTION&OUTPUT:

Result: Thus the C program to implement the priority scheduling algorithm was executed
successfully

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

41
Ex.No : 4 SIMULATATIONofIPCinUNIX

AIM:

To write a C program to implement inter process communication.

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

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

AIM: To write a C program to implement inter processcommunication SHARED MEMORY FOR

WRITERPROCESS

ALGORITHM:

1. Writer requests the entry to critical section.

2. If allowed i.e. wait() gives a true value, it enters and performs the write. If not allowed, it keeps
on waiting.

3. It exits the critical

section. do {

//writer requests for critical section wait(wrt);

//performs the write

//leaves the critical section signal(wrt);

while(true);

Program:

#include<stdio.h>

int main()

// ftok to generate unique key

key_tkey=ftok("shmfile",65);

//shmgetreturnsanidentifierinshmid

intshmid=shmget(key,1024,0666|IPC_CREAT);

43
//shmattoattachtosharedmemory

charstr=(char)shmat(shmid,(void*)0,0);

cout<<"Write Data : ";

gets(str);

printf("Datawritteninmemory: %s\n",str);

//detachfromsharedmemory

shmdt(str);

return 0;

EXECUTION&OUTPUT:
SHARED MEMORY FOR READER PROCESS

AIM:

To write a C program to implement inter-process communication (IPC) using shared memory for the
reader process in a UNIX environment.

DESCRIPTION:

In inter-process communication using shared memory, multiple reader processes can read data
simultaneously. However, synchronization is essential to prevent conflicts between readers and writers
accessing the shared memory.

This implementation follows the Reader-Writer problem with reader preference, where multiple readers
are allowed to read at the same time, but writers must have exclusive access to the shared memory.

To achieve synchronization, two semaphores are used:

 mutex – to protect the readcnt variable (number of readers currently reading).


 wrt – to ensure exclusive access for writers when no readers are present.

ALGORITHM (Reader Process):

1. The reader requests entry to the critical section.


2. If allowed:
o It increments the readcnt (number of active readers).
o If it is the first reader, it performs wait(wrt) to block writer access.
o It then signals mutex to allow other readers to enter.
o The reader performs the read operation on shared memory.
o After reading, the reader enters the exit section:
 It decrements readcnt.
 If it is the last reader (readcnt == 0), it signals wrt to allow writers to proceed.
o Finally, it signals mutex to release access.
3. If not allowed, the reader keeps waiting.

49
PROGRAM:

#include<stdio.h>

int main()

// ftok to generate unique key

key_tkey=ftok("shmfile",65);

//shmgetreturnsanidentifierinshmid

intshmid=shmget(key,1024,0666|IPC_CREAT);

//shmattoattachtosharedmemory

char str = (char) shmat(shmid,(void*)0,0);

printf("Datareadfrommemory:%s\n",str);

//detachfromsharedmemory

shmdt(str);

// destroy the shared memory

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.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

52
Ex.No:5 IMPLEMENTATIONOFDEADLOCK -BANKERSALGORITHM

AIM:
To write a UNIX C Program for the Implementation of Banker's

PROBLEMDESCRIPTION:

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

The Banker’s Algorithm is divided into two parts:

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
ofthe 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 Processescannot complete
its execution.

ALGORITHM:

Step 1: Start the program.

Step 2: Declare the necessary memory and data structures for processes, resources, allocation matrix,
maximum matrix, need matrix, and available resources.

Step 3: Read the number of processes and resources from the user.
Then, read the allocation matrix, maximum requirement matrix, and available resources vector.

Step 4: Apply the Banker's Algorithm:

 For each process, check if its needs can be satisfied with the currently available resources.
 If yes, simulate its execution by adding its allocated resources back to the available pool after
execution.
 Mark the process as completed and continue to the next.

Step 5: If all processes can finish safely in some order, the system is in a safe state.
If one or more processes cannot proceed, the system is in an unsafe (deadlock) state.

Step 6: Display the result:

 Print the safe sequence if found.


 Otherwise, indicate that the system is in deadlock or unsafe.

Step 7: Stop the program.

PROGRAM:

#include<stdio.h>

int main()

//P0,P1,P2,P3,P4aretheProcessnameshere int n,

m, i, j, k;

n=5;//Numberofprocesses

m=3;//Numberofresources
54
intalloc[5][3]={ {0,1,0}, //P0 //AllocationMatrix

{ 2, 0,0 },//P1

{ 3,0,2 },//P2

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

intmax[5][3]={{7,5, 3},// P0 //MAXMatrix

{ 3,2,2 },//P1

{ 9,0,2 },//P2

{ 2,2,2 },//P3

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

intavail[3]={3,3,2};// AvailableResources int

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

for(k=0;k<n;k++){ f[k]

= 0;

intneed[n][m];

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

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

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

inty=0;

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

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

if(f[i]==0){

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

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

flag = 1;

break;

}}

if (flag == 0) {

ans[ind++]=i;

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

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

f[i] =1;

}}}}

printf("FollowingistheSAFESequence\n"); for

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

printf("P%d->",ans[i]);

printf("P%d",ans[n-1]);

return (0);

56
EXECUTION&OUTPUT:

Result: Thus the Banker’s algorithm was implemented successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

57
Ex.No.:6 PAGEREPLACEMENTALGORITHMS

AIM:
To write a program in C to implement page replacement algorithm FIFO

PROBLEMDESCRIPTION:

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 nextpage without calculating the next page. Take the
nextpageinthepagereferencestringandcheckifthepageisalreadypresentinthememoryornot. 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:

1. Start the program.


2. Declare the frame size (i.e., the number of page frames available in memory).
3. Get the number of pages to be inserted from the user.
4. Read the page reference string (the sequence of pages requested).
5. Declare required arrays:
o A stack or queue to simulate page frames.
o A counter or time array to track the usage of pages for LRU selection.
6. For each page in the reference string:
o If the page is already in the frame, mark it as recently used.
o If the page is not in the frame:
 If there is space available, insert the page.
58

If the frame is full, select the least recently used (LRU) page using the counter value
and replace it with the new page.
o Update the counter/timestamp for all pages accordingly.
7. Display the page replacement process and the page fault count.
8. Stop the program.

Program
#include<stdio.h>
intfindLRU(inttime[],intn){

inti,minimum=time[0],pos=0; for(i =
1; i < n; ++i){

if(time[i]<minimum){

minimum=time[i];
pos = i;
}
}
returnpos;
}

intmain()
{
intno_of_frames,no_of_pages,frames[10],pages[30],counter=0,time[10],flag1,flag2,i,j, pos,
faults = 0;

printf("Enternumberofframes:");
scanf("%d", &no_of_frames);
printf("Enternumberofpages:");
scanf("%d", &no_of_pages);

printf("Enterreferencestring:");
for(i=0;i<no_of_pages;++i){
scanf("%d", &pages[i]);

}
59
for(i=0;i<no_of_frames;++i){ frames[i]
= -1;

}
for(i=0;i<no_of_pages;++i){
flag1 = flag2 = 0;

for(j=0;j<no_of_frames;++j){
if(frames[j]==pages[i]){

counter++;
time[j]=counter;
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;

60
}
printf("\n");
for(j=0;j<no_of_frames;++j){
printf("%d\t", frames[j]);

}
}
printf("\n\nTotalPageFaults=%d",faults);
return 0;

}
EXECUTION&OUTPUT:

61
Optimal Page Replacement Algorithm

AIM:

To write a C program to implement the Optimal Page Replacement Algorithm for memory management.

ALGORITHM:

1. Read the number of pages in the reference string and the cache (frame) size.
2. Let the cache size be N.
o Insert the first N elements from the reference string into the cache directly.
o Print the current cache content.
o Increment the page fault count for each insertion.
3. For the remaining elements in the reference string, do the following:
o There are two cases:
 The element is already present in the cache.
 The element is not present in the cache.
4. If the element is not present in the cache:
o Use the function isPresent() to check if the element exists in the cache.
o For all elements in the cache, calculate the future distance (how far in the future each page
will be used again) using a function like findLength().
o Identify the page with the maximum distance (i.e., the one not needed for the longest time
or not needed again at all) using the findMax() function.
o Replace that page in the cache with the current page from the reference string.
o Increment the page fault count.
5. If the element is already in the cache, do nothing.
6. After processing all pages, print the total number of page faults.

PROGRAM:

#include<stdio.h>
int main()
{
//variabledeclarationandinitialization
intframes_number,pages_number,frames[10],faults,pages[30],temp[10],flag1,flag2,flag3,i,j, k,
pos, max, miss = 0;

//code to input the frame number


printf("Enternumberofframes:");

62
scanf("%d", & frames_number);

//code to input number of pages


printf("Enternumberofpages:");

scanf("%d", &pages_number);

//codetodefinereferencestring,pagenumbers,andframenumbers
printf("Enter page reference string: ");

for(i=0;i<pages_number;++i){
scanf("%d", &pages[i]);

}
for(i=0;i<frames_number;++i){
frames[i] = -1;
}

for(i=0;i<pages_number;++i){
flag1 = flag2 = 0;
for(j=0;j<frames_number;++j){
if(frames[j] == pages[i]){
flag1=flag2=1; break;

}
}

//definitionoftheflagatthestartingofthestring
if(flag1 == 0){
for(j=0;j<frames_number;++j){
if(frames[j] == -1)

{
faults++;

frames[j]=pages[i];

63
flag2 = 1;
break;
}
}
}

//definitionoftheflagatthemidposition
if(flag2==0){
flag3=0;
for(j=0;j<frames_number;++j){
temp[j] = -1;

for(k=i+1;k<pages_number;++k){
if(frames[j] == pages[k]){
temp[j]=k;
break;
}

}
}
for(j=0;j<frames_number;++j){
if(temp[j] == -1){
pos = j;
flag3=1;

break;

}
}

//definitionofflagattherearposition if(flag3
==0){
max=temp[0];
pos = 0;

for(j=1;j<frames_number;++j){if(temp[j]>max){ max =
64
temp[j];
pos=j;
}
}
}
frames[pos]=pages[i];
miss++;
}
printf("\n");

for(j=0;j<frames_number;++j){
printf("%d\t", frames[j]);
}

}
printf("\n\nTotalPagemiss=%d",miss);
return 0;

EXECUTION&OUTPUT:

RESULT: Thus C program to implement Optimal replacement algorithm was implemented


successfully.

65
FIFO Page Replacement Algorithm

AIM:

To write a C program to implement the FIFO (First-In-First-Out) page replacement algorithm.

ALGORITHM:

1. Start the program.


2. Declare the cache size based on the number of available page frames.
3. Read the number of pages and the page reference string from the user.
4. For each page in the reference string:
o Check whether the page is already present in memory (cache).
o If not present:
 If there is space available in the queue (memory), insert the page.
 Otherwise, replace the oldest page (i.e., the front of the queue) with the new page.
 Increment the page fault count.
5. Maintain a queue structure to store the current pages in memory (in FIFO order).
6. Insert the required pages into memory using queue operations.
7. Detect and count page faults and replacements when a page is not found in memory.
8. Display the total number of page faults and the final state of the memory.
9. Stop the program.

PROGRAM:
#include<stdio.h>in
t main()

{
inti,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\nENTERTHENUMBEROFPAGES:\n");
scanf("%d",&n);
printf("\nENTERTHEPAGENUMBER:\n");

for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\nENTERTHENUMBEROFFRAMES:");
scanf("%d",&no);

66
for(i=0;i<no;i++)
frame[i]=-1;
j=0;
printf("\trefstring\tpageframes\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)
{

67
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);

}
printf("\n");
}
printf("PageFaultIs%d",count);
return 0;

EXECUTION&OUTPUT:

Result: Thus c program to implement FIFO algorithm was implemented successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

68
Ex. No. 7a – Memory Management Scheme using Best Fit

AIM:

To write a C program to implement the Memory Management Scheme using the Best Fit Algorithm.

ALGORITHM:

1. Get the number of processes and the number of memory blocks from the user.
2. Read the size of each memory block and the size of each process request.
3. For each process, select the best-fit memory block, i.e., the smallest available block that is large
enough to accommodate the process.
4. Allocate the selected block to the corresponding process.
5. Display the allocation result, showing which block is allocated to which process.
6. Optionally, display the internal fragmentation (unused space in allocated blocks) to track wasted
memory.
7. Stop the program.

PROGRAM:
#include<stdio.h>

intmain()
{

intfragments[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("\nEntertheTotalNumberofBlocks:\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++)
{

69
printf("BlockNo.[%d]:\t",m+1);
scanf("%d",&block[m]);
}

printf("EntertheSizeoftheFiles:\n");
for(m=0;m<number_of_files;m++)
{
printf("FileNo.[%d]:\t",m+1);
scanf("%d",&file[m]);
}
for(m=0;m<number_of_files;m++)
{
for(n=0;n<number_of_blocks;n++)

{
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;

70
}
}
printf("\nFileNumber\tFileSize\tBlockNumber\tBlockSize\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;
}

EXECUTION&OUTPUT:

71
Result: Thus c program to implement best fit was executed successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

72
Ex. No. 7b – Memory Management Scheme using First Fit

AIM:

To write a C program to implement the memory management scheme using the First Fit algorithm.

ALGORITHM:

1. Get the number of processes and the number of memory blocks from the user.
2. Read the size of each memory block and the size of each process request.
3. For each process, scan the memory blocks from the beginning and:
o If the block size is greater than or equal to the process size:
→ Allocate the process to that block.
→ Mark the block as allocated.
→ Break and move to the next process.
o Else:
→ Continue checking the next block.
4. Display the allocation results, showing which process is allocated to which memory block.
5. Stop the program.

PROGRAM:

#include<stdio.h>in
t main()
{

staticintblock_arr[10],file_arr[10];
int fragments[10],blocks[10],files[10];
intm,n,number_of_blocks,number_of_files,temp;
printf("\nEnter the Total Number of Blocks:\t");
scanf("%d", &number_of_blocks);

printf("EntertheTotalNumberofFiles:\t");
scanf("%d", &number_of_files);
printf("\nEnter the Size of the Blocks:\n");
for(m = 0; m < number_of_blocks; m++)
{

73
printf("BlockNo.[%d]:\t",m+1);
scanf("%d",&blocks[m]);
}

printf("EntertheSizeoftheFiles:\n");
for(m=0;m<number_of_files;m++)
{
printf("FileNo.[%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)
{
file_arr[m]=n;

break;
}
}
}
fragments[m] = temp;
block_arr[file_arr[m]]=1;

}
printf("\nFileNumber\tBlockNumber\tFileSize\tBlockSize\tFragment"); for(m
= 0; m < number_of_files; m++)

74
{
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;
}

EXECUTION&OUTPUT:

75
Result: Thus c program to implement best fit was implemented successfully.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

76
Ex. No. 7c – Memory Management Scheme using Worst Fit

AIM:

To write a C program to implement the Memory Management Scheme using the Worst Fit algorithm.

EXERCISE:

Given memory partitions of 100 KB, 500 KB, 200 KB, 300 KB, and 600 KB (in order), how would the
First Fit, Best Fit, and Worst Fit algorithms place the following processes (in order):
212 KB, 417 KB, 112 KB, and 426 KB?

Question: Which algorithm makes the most efficient use of memory?


Can Worst Fit be more efficient in certain cases?

ALGORITHM:

Step 1: Input the number and sizes of the memory blocks.

Step 2: Input the number and sizes of the processes to be allocated.

Step 3: For each process:

 Search for the largest available memory block that can accommodate the process.
 This block is selected using the Worst Fit strategy (i.e., maximum available space).

Step 4: If a suitable block is found:

 Allocate the process to that block.


 Update the size of the memory block to reflect the remaining space.

Step 5: If no suitable block is found, skip the process and move on to the next one.

Step 6: Display the block allocations and, optionally, the internal fragmentation.

Step 7: Stop the program.

PROGRAM:
#include<stdio.h>in
t main()

{
77
int fragments[10],blocks[10],files[10];

intm,n,number_of_blocks,number_of_files,temp,top=0; static
int block_arr[10], file_arr[10];

printf("\nEntertheTotalNumberofBlocks:\t");
scanf("%d",&number_of_blocks);

printf("EntertheTotalNumberofFiles:\t");
scanf("%d",&number_of_files);
printf("\nEntertheSizeoftheBlocks:\n");
for(m= 0;m<number_of_blocks;m++)
{
printf("BlockNo.[%d]:\t",m+1);

scanf("%d",&blocks[m]);
}

printf("EntertheSizeoftheFiles:\n");
for(m=0;m<number_of_files;m++)

{
printf("FileNo.[%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)
78
{

file_arr[m]=n;
top = temp;
}
}
}
fragments[m]=top;
block_arr[file_arr[m]]=1;
top=0;
}

}
printf("\nFileNumber\tFileSize\tBlockNumber\tBlockSize\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;

79
EXECUTION&OUTPUT:

80
Result: Thus c program for worst fit was executed successfully

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

81
Ex. No: 8 – Implementation of Disk Scheduling Algorithms

AIM:

To write a C program to implement Disk Scheduling Algorithms including:

 First Come First Served (FCFS)


 Shortest Seek Time First (SSTF)
 SCAN (Elevator Algorithm)

PROBLEM DESCRIPTION:

Disk Scheduling is the process of deciding the order in which disk I/O requests should be serviced from the
ready queue.
Efficient scheduling can improve the access time and disk bandwidth.

Key Concepts:

 Access Time:
Total time to access data on the disk, consisting of:
o Seek Time: Time for the disk arm to move the head to the correct cylinder.
o Rotational Latency: Time for the desired sector to rotate under the read/write head.
 Disk Bandwidth:
Total bytes transferred divided by the total time between the first request and the last data transfer.

PROCEDURE:

1. Input the maximum number of cylinders, the work queue (list of disk I/O requests), and the initial
head position.
2. FCFS (First Come First Serve):
o Serve the requests in the exact order they arrive.
o No reordering of the queue.
o Every request is serviced → no starvation.
o Calculate and display total seek time.
3. SSTF (Shortest Seek Time First):
o Select the request closest to the current head position.
o Minimizes the seek time at each step.
o Calculate and display total seek time.
4. SCAN (Elevator Algorithm):
o Disk arm moves in one direction servicing requests until the end is reached.
o Then, it reverses direction and services remaining requests.
o The head continuously scans back and forth.
82
o Calculate and display total seek time.
5. Display the seek sequence and the total seek time for each algorithm.
6. End the program.

ALGORITHM (General for All Three Algorithms):

1. Let request[] be the array containing the requested track numbers (I/O requests).
Let head be the initial position of the disk head.
2. For each algorithm:
o Take the track requests one by one (in order or optimized by algorithm).
o Calculate the absolute difference between the current head position and the requested track.
o Add this difference to the total seek count.
o Update the head position to the current track.
3. Repeat until all tracks have been serviced.

Program :

#include<stdio.h>i

nt main()

intqueue[20],n,head,i,j,k,seek=0,max,diff;

float avg;
printf("Enterthemaxrangeofdisk:");

scanf("%d",&max);

printf("Enterthesizeofqueuerequest:");

scanf("%d",&n);

printf("Enterthequeueofdiskpositionstoberead:"); for(i=1;i<=n;i++)

scanf("%d",&queue[i]);

printf("Entertheinitialheadposition:");

scanf("%d",&head);

queue[0]=head;

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

83
{

diff=abs(queue[j+1]-queue[j]);

seek+=diff;

printf("Diskheadmovesfrom%dto%dwithseek:%d\n",queue[j],queue[j+1],diff);

printf("Totalseektimeis%d\n",seek);

avg=seek/(float)n;

printf("Averageseektimeis%f\n",avg);

return 0;

EXECUTION&OUTPUT:

SSTF:

ALGORITHM: Shortest Seek Time First (SSTF)

1. Let Request[] be an array storing the track numbers that have been requested.
Let head be the current position of the disk head.
2. For all tracks in the Request[] array that have not yet been serviced, calculate the absolute distance
from the current head position.
3. Select the track with the minimum distance from the current head among the unserviced tracks.
4. Increment the total seek count by this minimum distance.
5. Update the head position to the track that was just serviced.
6. Repeat Steps 2–5 until all tracks in the request array have been serviced.

84
PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<math.h>i

nt main()

intqueue[100],t[100],head,seek=0,n,i,j,temp;

float avg;

// clrscr();

printf("*SSTFDiskSchedulingAlgorithm*\n");

printf("Enter the size of Queue\t");

scanf("%d",&n);

printf("EntertheQueue\t");

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

scanf("%d",&queue[i]);

printf("Entertheinitialheadposition\t");

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])

85
{

temp=t[i];t[i]=t[j];

t[j]=temp;

temp=queue[i];

queue[i]=queue[j];

queue[j]=temp;

}
}

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

seek=seek+abs(head-queue[i]);

head=queue[i];

printf("\nTotalSeekTimeis%d\t",seek); avg=seek/(float)n;

printf("\nAverageSeekTimeis%f\t",avg);

return 0;

EXECUTION&OUTPUT:

SCAN:
ALGORITHM: SCAN (Elevator Algorithm)

86
1. Let Request[] represent an array storing the indexes of tracks that have been requested, in ascending
order of their time of arrival.
Let head represent the current position of the disk head.
2. Let direction indicate whether the disk head is moving left (toward track 0) or right (toward the
maximum track number).
3. In the direction in which the head is moving, service all the tracks one by one, until the end of the
disk is reached.
4. For each track serviced, calculate the absolute distance between the current head position and the
requested track.
5. Increment the total seek count with this distance.
6. Update the head position to the track just serviced.
7. Once the disk head reaches the end in the current direction, reverse the direction and repeat the
servicing process for the remaining tracks.

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;

floatavg;

printf("Enterthemaxrangeofdisk\n"); scanf("%d",&max);

printf("Entertheinitialheadposition\n");

scanf("%d",&head);

printf("Enterthesizeofqueuerequest\n"); scanf("%d",&n);

printf("Enterthequeueofdiskpositionstoberead\n");

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

scanf("%d",&temp);

if(temp>=head)

{
87
queue1[temp1]=temp;

temp1++;

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++)

{
88
if(queue2[i]<queue2[j])

{
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;

printf("Diskheadmovesfrom%dto%dwithseek%d\n",queue[j],queue[j+1],diff);

printf("Totalseektimeis%d\n",seek);

avg=seek/(float)n;

printf("Averageseektimeis%f\n",avg);

return 0;

89
}
EXECUTION&OUTPUT:

Result: Thus implemented disk scheduling algorithms.

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

90
Ex No: 9 IMPLEMENTATIONOFACCESSCONTROLMECHANISM
AIM:

Towritea‘C’programtoimplementvariousAccessControlMechanisminOperating
Systems.

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

Types of Access Control.


Based on the restrictions and access control to systems, we come across three main types:
discretionary access control (DAC), role based access (RBAC) and mandatory access control
(MAC).
Discretionary Access control, DAC: Discretionary access control is a means of restricting access
to objects based on the identity of subjects that try to operate or access them. The most
representative example is the mechanism of permissions established by the owner (user/group) of
the subject. Therefore, it’s the owner of the object who determines which users and with which
privileges they access his/her objects. This access mechanism is present in the majorityof
operatingsystems.In this type of accesscontrol its normal to use attributes(read, write,execute,

91
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…).

DACpermissions ina Windowsfile-


In the particular case of UNIX/Linux systems, the objects of the system (files, directories, etc)
include three attributes: read (r), write (w) and execute (x). These permissions are assigned by the
user for the group and others (users that are not owners and don’t belong the group).
In Linux, with the ls -l command we can visualize the basic DAC permissions. In the following
example we can see a system, where user1, who belongs to group1, has fixedthe read/write/execute
permissions (rwx) to himself as the owner. The users that belong to the same group (grupo1) have
the same read and write permissions (rw-) and any other user only has a read permission (r--):

Discretionalaccesspermissions(DAC),traditionalin*NIXsystems-
This way, any read, write or execute action that doesn’t comply with these permission will be
denied.

92
-usuario2canreadbutnotmodifyusuario1’sfichero1becauseoftheassignedpermissions-

Other properties exist such as ACLs (access control list) or other a


href="http://en.wikipedia.org/wiki/File_system_permissions" rel="external">special permissions
such as sticky bit, or setuid, setgid (Linux) permissions that add more options to the DAC but are
out of the introductory reach of this part.

Role-BasedAccessControl(RBAC)
Discretionalaccesscontrolsdon’tprovideasufficientgranularitytoenableamoredefined and
structured segmentation in a complex system with multiple users and functions. In this case, a role
mechanism offers greater versatility. Role-based access control consists in the definition of roles
that have been attributed a number of characteristics applied to the permissions and actions that
they can carry out, including controlling other roles. It is, in a way, a hierarchical system of
classes. Often used in organizations with a great number of users where different work groups or
departments with different functions are integrated, such as for example systems, development,
commercial, general service departments. With this mechanism, access to objects and tasks can be
efficiently segmented and organized. Notable cases of these mechanisms are LDAP, Active
DirectoryofMicrosoftWindowsorFreeIPAofFedora/Redhat.SomeUNIXsystemssuch as Solarisor
AIXall implement this system of privileges.

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
establishedMAC policies will beapplied to determineif theoperation is allowed, even when it has
complied with other security controls. In contrast with the discretionary access control, the user
canmodifypermissionsandtagsbutcan’tfixaccesscontrolsthatsupposeaviolationofthe

93
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 SELinuxin Linux/Redhat/Centos/Fedora distributions or AppArmorin
Linux SuSE.
.

Typesofaccesscontrol-

94
Viva-Vocequestions:

1. Define Access Control


2. What are the types of Access Control?
3. Why Access Controlis needed?
4. Where this access control is implemented?
5. Where this Access Control information is stored?

Experiments addressing COs:

The experiments mentioned above address CO5

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

Total

Result

Access Control Mechanism have been exeuted successfully.

95
Ex No: 10 IMPLEMENTATIONOFCRYPTOGRAPHICALGORITHMS
AIM:

Towritea‘C’programtoimplementvariousCryptographyAlgorithmssuchasRSA,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.

EncryptionTypes/Methods

AsymmetricEncryption
In public-key encryption schemes, the encryption keyis publishedforanyone 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
asecretdocumentin1973.Beforethat,allencryptionschemes were symmetric-key (also
called private-key).

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

EncryptionAlgorithms

TripleDES
Triple DES was designed to replace the original Data Encryption Standard (DES)
algorithm, which hackers learned todefeatwithease.Atonetime,TripleDES was the
recommended standardandthe mostwidelyusedsymmetricalgorithm in the industry.
TripleDESusesthreeindividualkeyswith56bitseach.The total key length adds
upto168bits,butexpertssaythat112-bitsinkey strength is more like it.Though it is
slowly being phased out, Triple DES is still a dependable hardware encryption
solution for financial servicesandother 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.

97
EncryptionStandards
The reareanumberofstandardsrelated tocryptography. Herearethefollowing standards
for encryption:
 DataEncryptionStandard(nowobsolete)
 AdvancedEncryptionStandard
 RSA(theoriginalpublic-keyalgorithm)
 OpenPGP

FileEncryptionOverview
File system-level encryption, often called file and folderencryption,isa formofdisk
encryption where individual files or directories are encrypted bythefilesystem itself.

DiskEncryptionOverview
Disk encryption is a technology that protects information by converting it into
unreadable code that cannot be deciphered easily by authorized users. Disk
encryption uses disk encryption softwareorhardwaretoencrypteverybitof data that
goes on a disk or disk volume.

EmailEncryptionOverview

Emailencryptionisencryptionofemailmessagesdesignedtoprotectthecontent from
being read by entities other than the intended recipients. Email encryption may
also include authentication. Email is not secure and may disclose sensitive
information. Most emails are currently transmitted in the clear (not encrypted)
form. By means of some available tools, people other than designated recipients
can read the email content. Email encryption traditionally uses one of two
protocols, either TLS or end-to-end encryption. Within end-to-end encryption,
there are several options, including PGP and S/MIME protocols.

98
EncryptionBestPractices
1. Know thelaws: When it comes to safeguarding the personally identifiable
information, organizations must adhere to many overlapping, privacy-
related regulations. The top six regulations that impactmany
organizationsinclude:FERPA,HIPAA,HITECH,COPPA,PCIDSS andstate-
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.
DepartmentofHealthandHumanServices(HHS)turnstotheNational Institute
of Standards and Technology (NIST) for recommended encryption- level
practices. HHS and NIST have both produced robust documentation for
adhering to HIPAA’sSecurity Rule.NISTSpecialPublication800-111takes a
broad approach to encryption on user devices. In a nutshell, it states that
when there is even a remote possibility of risk,encryption needsto be in
place. FIPS 140-2, which incorporates AESintoitsprotocols, 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 meetsFIPS 140-2 requirementshas a
cryptographic erase function that “leverages the encryption of target data
by enabling sanitization of the target data’s encryption key, leaving onlythe
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 orsending
data over the internet needs Transport Layer Security (TLS), a protocol for
transmitting data over a network, and AES encryption. When anemployee
accesses aninstitution’slocal network, asecure VPN
99
connection is essential when ePHIisinvolved.Also,beforeputtinga 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 violateFERPA.
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.

Algorithm: Working of RSA Algorithm

RSA (Rivest–Shamir–Adleman) is an asymmetric encryption algorithm that uses a


pair of keys: a public key and a private key. The public key is used for encryption, and
the private key is used for decryption.

Steps:

1. Select two prime numbers, p and q.


2. Compute n = p × q, which is used as the modulus for both the public and private
keys.
3. Calculate Euler's totient function:
φ(n) = (p - 1) × (q - 1)
4. Choose an integer e such that:
o 1 < e < φ(n)
o gcd(e, φ(n)) = 1
(i.e., e is co-prime to φ(n) and is the public key exponent)
5. Determine d, the private key exponent, such that:
o d × e ≡ 1 (mod φ(n))
(i.e., d is the modular multiplicative inverse of e modulo φ(n))
6. Encryption:
o Convert the message m into ciphertext c using the public key (e, n)
o c = m^e mod n
7. Decryption:
o Recover the original message m using the private key (d, n)
o m = c^d mod n

100
Program:
#include<stdio.h>

#include<math.h>

//tofindgcd

intgcd(inta,inth)

inttemp;

while(1)

temp=a%h;

if(temp==0)

return h;

a=h;

h=temp;

intmain()

//2randomprimenumbers

double p = 3;

double q = 7;

doublen=p*q;

double count;

doubletotient=(p-1)*(q-1);

101
//publickey

//estandsforencrypt

double e=2;

//forcheckingco-primewhichsatisfiese>1

while(e<totient){

count=gcd(e,totient);

if(count==1)

break;

else

e++;

//private key

//dstandsfordecrypt

double d;

//kcanbeanyarbitraryvalue double

k = 2;

//choosingdsuchthatit satisfiesd*e=1+k*totient d = (1

+ (k*totient))/e;

double msg = 12;

doublec=pow(msg,e);

double m = pow(c,d);

c=fmod(c,n);

102
m=fmod(m,n);

printf("Messagedata=%lf",msg);

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);

printf("\nEncrypted data = %lf",c);

printf("\nOriginalMessageSent=%lf",m); return

0;

OUTPUT:

DESALGORITHM

What is DES Encryption 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.

103
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>in

t main()

intarray_a1[30],array_a2[30],array_a3[30],array_a4[30],array_a5[30],array_a6[30],
array_a7[30], array_a8[30];

intdiv,count,j,key, m,plaintext,temp,dec=0;

printf("\nEnter a Plain-Text value:\t");

scanf("%d", &plaintext);

printf("\nEnter the Key:\t");

scanf("%d", &key);

printf("\nEntertheBit-Stream\n");

for(count=0;count<plaintext;count++)

scanf("%d",&array_a1[count]);

div=plaintext/2;

temp = div - key;

for(count=0;count<=temp; count++)

array_a3[count]=0;

dec++;

dec=dec-1;

104
printf("EntertheKeyBitStream\n");

for(count=0;count<key;count++)

scanf("%d",&array_a3[dec++]);

for(count=0;count<2;count++)

printf("%d",array_a8[count]);

printf("LeftHand\n");

for(count=0;count<div;count++)

array_a5[count]=array_a1[count];

printf("%d", array_a1[count]);

printf("RightHand\n");

for(count=div;count<plaintext;count++)

array_a2[count]=array_a1[count];

printf("%d", array_a1[count]);

for(j=0,m=div;j<dec,m<plaintext;j++,m++)

if(array_a2[m]==1&&array_a3[j] ==1)

array_a6[j]= 0;
105
}

elseif(array_a2[m]==1&&array_a3[j] ==0)

array_a6[j]=m;

else

array_a6[j]= 0;

printf("\nFirstXOR\n");

for(count=0;count<div;count++)

printf("%d",array_a6[count]);

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

if(array_a5[m]=1&&array_a6[j]==1)

array_a4[j]= 0;

elseif(array_a5[m]=1&&array_a6[j]==0)

array_a4[j]=m;

elseif(array_a5[m]==0&&array_a6[j] ==1)
106
{

array_a4[j]= 0;

printf("\nSecond XOR\n");

for(count=0;count<div;count++)

printf("%d",array_a4[j]);

return 0;

107
Viva-Vocequestions:

1. What is cryptography?
2. What exactly are encryption and decryption?
3. What is plaintext or cleartext?
4. What is cipher text?
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?

Experiments addressing COs:

The experiments mentioned above address CO5

Assessment of an Individual experiment

Algorithm

Program

Output

Viva

Total

Result :

Towritea‘C’programtoimplementvariousCryptographyAlgorithmssuchasRSA,DEA, Blowfish was


implemented successfully.

108
109

You might also like