Cs6413-Os Lab Manual-Backup 2 New
Cs6413-Os Lab Manual-Backup 2 New
AIM
To execute the commands in unix.
GENERAL COMMANDS
pwd
o This command prints the current working directory
ls
o This command displays the list of files in the current working directory.
$ls –l Lists the files in the long format
$ls –t Lists in the order of last modification time
$ls –d Lists directory instead of contents
$ls -u Lists in order of last access time
cd
o This command is used to change from the working directory to any other
directory specified.
$cd directoryname
cd ..
o This command is used to come out of the current working directory.
$cd ..
mkdir
o This command helps us to make a directory.
$mkdir directoryname
rmdir
o This command is used to remove a directory specified in the command line. It
requires the specified directory to be empty before removing it.
$rmdir directoryname
cat
o This command helps us to list the contents of a file we specify.
$cat [option][file]
cat > filename – This is used to create a new file.
cat >>filename – This is used to append the contents of the file
cp
o This command helps us to create duplicate copies of ordinary files.
$cp source destination
mv
o This command is used to move files.
$mv source destination
ln
o This command is to establish an additional filename for the same ordinary file.
$ln firstname secondname
rm
o This command is used to delete one or more files from the directory.
$rm [option] filename
$rm –i Asks the user if he wants to delete the file mentioned.
who am i
o This command tells us as to when we had logged in and the system’s name
for the
o connection being used.
$who am i
date
o This command displays the current date in different formats.
echo
o This command will display the text typed from the keyboard.
$echo, Eg: $echo Have a nice day
RESULT
Thus the basic unix commands were executed and verified.
VIVA QUESTIONS
1. What is a directory?
AIM
To write a program for implementing process management using the following
system calls of UNIX operating system: fork, exec, getpid, exit, wait, close.
ALGORITHM:
1. Start the program.
2. Read the input from the command line.
3. Use fork() system call to create process, getppid() system call used to get the parent
process ID and getpid() system call used to get the current process ID
4. execvp() system call used to execute that command given on that command line
argument
5. execlp() system call used to execute specified command.
6. Open the directory at specified in command line input.
7. Display the directory contents.
8. Stop the program.
PROGRAM:
#include
main(int arc,char*ar[])
{
int pid;
char s[100];
pid=fork();
if(pid0)
{
wait(NULL);
printf("\n Parent Process:\n");
printf("\n\tParent Process id:%d\t\n",getpid());
execlp("cat","cat",ar[1],(char*)0); error("can’t execute cat %s,",ar[1]);
} else {
printf("\nChild process:");
printf("\n\tChildprocess parent id:\t %d",getppid());
sprintf(s,"\n\tChild process id :\t%d",getpid());
write(1,s,strlen(s));
printf(" ");
printf(" ");
printf(" ");
execvp(ar[2],&ar[2]); error("can’t execute %s",ar[2]);
}
}
RESULT: Thus the program for process management was written and successfully
executed.
EX NO:1 (b) Implementation of directory management using the following system calls of
UNIX operating system: opendir, readdir.
AIM: To write a program for implementing Directory management using the following
system calls of UNIX operating system: opendir, readdir.
ALGORITHM:
1.Start the program.
2. Open the directory at specified in command line input.
3. Display the directory contents.
4. Stop the program.
PROGRAM:
#include
#include
#include
main(int c,char* arg[])
{
DIR *d;
struct dirent *r;
int i=0; d=opendir(arg[1]);
printf("\n\t NAME OF ITEM \n");
while((r=readdir(d)) != NULL)
{
printf("\t %s \n",r->d_name);
i=i+1;
}
printf("\n TOTAL NUMBER OF ITEM IN THAT DIRECTORY IS %d \n",i);
}
rr_output.doc
ipc_pipe_output.doc
pro_con_prob_output.doc
TOTAL NUMBER OF ITEM IN THAT DIRECTORY IS 8
RESULT: Thus the program for directory management was written and successfully
executed
AIM:
To write a program using the I/O system calls of UNIX operating system (open,
read, write, etc)
ALGORITHM:
1. Start the program.
2. Read the input from user specified file.
3. Write the content of the file to newly created file.
4. Show the file properties (access time, modified time, & etc,.)
5. Stop the program.
PROGRAM:
#include<stdio.h>
#include<sys/stat.h>
#include<time.h>
main(int ag,char*arg[])
{
char buf[100];
struct stat s;
int fd1,fd2,n;
fd1=open(arg[1],0);
fd2=creat(arg[2],0777);
stat(arg[2],&s);
if(fd2==-1)
printf("ERROR IN CREATION");
while((n=read(fd1,buf,sizeof(buf)))>0)
{
if(write(fd2,buf,n)!=n)
{
close(fd1);
close(fd2);
}
}
printf("\t\n UID FOR FILE.......>%d \n FILE ACCESS TIME.....>%s \n FILE
MODIFIED TIME........>%s \n FILE I-NODE NUMBER......>%d \n
PERMISSION FOR FILE.....>%o\n\n",s.st_uid,ctime
(&s.st_atime),ctime(&s.st_mtime),s.st_mode);
close(fd1);
close(fd2);
}
OUTPUT:
[root@localhost ~]# cc iosys.c
[root@localhost ~]# ./a.out
UID FOR FILE.......>0
FILE ACCESS TIME.....>Thu Apr 8 01:23:54 2011
FILE MODIFIED TIME........>Thu Apr 8 01:23:54 2011
FILE I-NODE NUMBER......>33261
PERMISSION FOR FILE.....>1001101014
RESULT:
Thus the program using the I/O system calls was written and successfully
executed.
AIM:
To write a program to simulate UNIX commands like ls, grep, etc.
ALGORITHM:
1. Start the program.
2. Read the input through command line.
3. Open the specified file.
4. Options (c & i) are performed.
5. Stop the program.
PROGRAM:
#include<stdio.h>
#include<string.h>
main(int ag,char* arg[])
{
char buf[200],line[200];
int i,j,n,fd1,count=0,opt;
if(ag==4)
{
fd1=open(arg[3],0);
if(strcmp(arg[1],"-c")==0)
opt=2;
if(strcmp(arg[1],"-i")==0)
opt=3;
}
else if(ag==3)
{
fd1=open(arg[2],0);
opt=1;
}
if(fd1==-1)
printf("error in opening");
j=0;
switch(opt)
{
case 1:
while((n=read(fd1,buf,sizeof(line)))>0)
{
for(i=0;i<n;i++,j++)
{
if(buf[i]!='\n') line[j]=buf[i];
else
{
line[j]='\n';
if(strstr(line,arg[1])!=0)
write(1,line,j+1);
}
}
}
break;
case 2:
while((n=read(fd1,buf,sizeof(line)))>0)
{
for(i=0;i<n;i++,j++)
{
if(buf[i]!='\n') line[j]=buf[i];
else
{
line[j]='\n';
if(strstr(line,arg[2])!=0)
count=count+1;
j=-1;
}
}
}
printf("%d \n",count);
break;
case 3:
while((n=read(fd1,buf,sizeof(line)))>0)
{
for(i=0;i<n;i++,j++)
{
if(buf[i]!='\n') line[j]=buf[i];
else
{
line[j]='\n';
if(strcasestr(line,arg[2])!=0)
write(1,line,j+1);
j=-1;
}
}
}
break;
}
close(fd1);
}
OUTPUT:
[root@localhost ~]# cat tst sd
dsaASD[root@localhost ~]# ./a.out -i a tst
aA[root@localhost ~]# ./a.out -c a tst 1[root@localhost ~]# ./a.out -c A tst
1[root@localhost ~]# ./a.out -c sd tst 1[root@localhost ~]# ./a.out -c s tst 2
RESULT:
Thus the program to stimulate the UNIX commands was written and
successfully executed.
EVEN OR ODD
AIM
To write a shell program to find whether a number is even or odd.
PROCEDURE
1. Read the input number.
2. Perform modular division on input number by 2.
3. If remainder is 0 print the number is even.
4. Else print number is odd.
5. Stop the program.
PROGRAM
echo "Enter the number"
read num echo "enter the number"
read num if [ `expr $num % 2` -eq 0 ] then
echo "number is even"
else echo "number is odd"
fi
OUTPUT
Enter the number: 5
the number is odd.
RESULT
Thus the shell program was executed and verified successfully.
FACTORIAL OF NUMBER
AIM
To write a program to find the factorial of given number
PROCEDURE
1. Read a number
2. Initialize fact as 1
3. Initialize I as 1
4. While I is lesser than or equal to number
5. Multiply the value of I and fact and assign to fact
6. Increment the value of I by 1.
7. Print the result.
8. Stop the program.
PROGRAM
echo "enter the number"
read n
fact=1, i=1
while [ $i -le $n ]
do
fact=`expr $i \* $fact`
i=`expr $i + 1`
done
echo "the factorial number of $n is $fact”
OUTPUT
Enter the number : 4
The factorial of 4 is 24.
RESULT
Thus the shell program was executed and verified successfully.
VIVA QUESTIONS:
1) Primitive Scheduling algorithms: In this, the CPU can release the process even in the
middle of execution. For example: the CPU executes the process p1, in the middle of
execution the CPU received a request signal from process p2, then the OS compares the
priorities of p1&p2. If the priority p1 is higher than the p2 then the CPU continue the
execution of process p1. Otherwise the CPU preempts the process p1 and assigned to
process p2.
2) Non-Primitive Scheduling algorithm: In this, once the CPU assigned to a process the
processor does not release until the completion of that process. The CPU will assign to
some other job only after the previous job has finished.
Scheduling Criteria
Scheduling may use in attempting to maximum system performance. The scheduling
policy determines the importance of each of the criteria some commonly used criteria are.
• CPU utilization
It is the function of time, during which the processor is busy. The load on the system
affects the level of utilization that can be achieved. It may range from 0% to 100% on large
and expensive system. Time shared system, CPU utilization may be the primary
consideration.
• Throughput
It refers to the amount of work completed in a unit of time. The number of processes
the system can execute in a period of time. The higher the number, the work is done by the
system.
• Turnaround time
From the point of view of a particular process, the important criterion is how long it
takes to execute that process. The interval from the time of submission of a process to the
time of completion is the turnaround time. Turnaround time is the sum of the periods spent
waiting to get into memory, waiting in the ready queue, executing on the CPU, and doing
I/O.
• Waiting time
The CPU-scheduling algorithm does not affect the amount of time during which a
process executes or does I/O. It affects only the amount of time that a process spends
waiting in the ready queue. Waiting time is the sum of the periods spent waiting in the ready
queue.
• Response time
In an interactive system, turnaround time may not be the best criterion. Often, a
process can produce some output fairly early and can continue computing new results while
previous results are being output to the user. Thus, another measure is the time from the
submission of a request until the first response is produced. This measure, called response
time, is the time it takes to start responding, not the time it takes to output the response.
The turnaround time is generally limited by the speed of the output device.
AIM
To write a program for implement the round robin scheduling algorithm.
ALGORITHM
1. Start the process
} else {
for (j = 0; j < n; j++) {
if ((j != i) && (bt[j] != 0)) {
wt[j] += bt[i];
}
}
bt[i] = 0;
}
}
sum = 0;
for (k = 0; k < n; k++) {
sum = sum + bt[k];
}
} while (sum != 0);
for (i = 0; i < n; i++) {
tat[i] = wt[i] + a[i];
}
System.out.println("process\t\tBT\tWT\tTAT");
for (i = 0; i < n; i++) {
System.out.println("process" + (i + 1) + "\t" + a[i] + "\t" + wt[i] + "\t" + tat[i]);
}
float avg_wt = 0;
float avg_tat = 0;
for (j = 0; j < n; j++) {
avg_wt += wt[j];
}
for (j = 0; j < n; j++) {
avg_tat += tat[j];
}
System.out.println("Average wating time " + (avg_wt / n) + "\nAverage turn around
time" + (avg_tat / n));
}
}
OUTPUT
Enter number of process:
3
Enter burst Time:
Enter burst Time for 1
30 millisec
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23RESULT
24 Thus the round robin program was executed and verified successfully.
25
26
27EX.NO:3(b) CPU SCHEDULING: SHORTEST JOB FIRST(SJF)
SCHEDULING
28DATE :
29
30AIM
31 To write a program to implement the CPU scheduling algorithm for shortest job first.
32
33ALGORITHM
0 1. Start the program
1 2. Declare the array size
2 3. Get the number of processes and their burst time
3 4. Processes will be executed based on minimal burst time
4 5. Other processes will be preempted
5 6. For the processes preempted, waiting time will be calculated
6 7. Display the process burst time and their waiting time
7 8. Stop the program
34
35PROGRAM
import java.util.Scanner;
public class SJF {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n, BT[], WT[], TAT[];
System.out.println("Enter no of process");
n = sc.nextInt();
BT = new int[n + 1];
WT = new int[n + 1];
TAT = new int[n + 1];
float AWT = 0;
System.out.println("Enter Burst time for each process");
for (int i = 0; i < n; i++) {
System.out.println("Enter BT for process " + (i + 1));
BT[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
WT[i] = 0;
TAT[i] = 0;
}
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (BT[j] > BT[j + 1]) {
temp = BT[j];
BT[j] = BT[j + 1];
BT[j + 1] = temp;
temp = WT[j];
WT[j] = WT[j + 1];
WT[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
TAT[i] = BT[i] + WT[i];
WT[i + 1] = TAT[i];
}
OUTPUT
Enter no of process
3
Enter Burst time for each process
Enter BT for process 1
10 millisec
Enter BT for process 2
30 millisec
Enter BT for process 3
20 millisec
PROCESS BT WT TAT
1 10 0 10
2 20 10 30
3 30 30 60
***********************************************
Avg waiting time=13.333333 millisec
36 ***********************************************
37
38
39RESULT
40 Thus the shortest job first program was executed and verified successfully.
AIM
To write a program to implement the first come first serve CPU scheduling algorithm
41ALGORITHM
1. Start the process
2. Declare the array size
3. Get the number of processes and their burst time
4. Processes will be executed based on arrival priority
5. First process will be executed first and followed by others
6. Total waiting time and turnaround time will be calculated
7. Display the values
8. Stop the process
PROGRAM
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class FCFS {
public static void main(String args[]) throws Exception {
int n, AT[], BT[], WT[], TAT[];
float AWT = 0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter no of process");
n = Integer.parseInt(br.readLine());
BT = new int[n];
WT = new int[n];
TAT = new int[n];
AT = new int[n];
System.out.println("Enter Burst time for each
process\n******************************");
for (int i = 0; i < n; i++) {
System.out.println("Enter BT for process " + (i + 1));
BT[i] = Integer.parseInt(br.readLine());
}
System.out.println("***********************************************");
for (int i = 0; i < n; i++) {
System.out.println("Enter AT for process" + i);
AT[i] = Integer.parseInt(br.readLine());
}
System.out.println("***********************************************");
WT[0] = 0;
for (int i = 1; i < n; i++) {
WT[i] = WT[i - 1] + BT[i - 1];
WT[i] = WT[i] - AT[i];
}
for (int i = 0; i < n; i++) {
TAT[i] = WT[i] + BT[i];
AWT = AWT + WT[i];
}
System.out.println(" PROCESS BT WT TAT ");
OUTPUT
Enter no of process
3
Enter Burst time for each process
******************************
Enter BT for process 1
20 millisec
Enter BT for process 2
30 millisec
Enter BT for process 3
10 millisec
***********************************************
Enter AT for process0
10 millisec
Enter AT for process1
20 millisec
Enter AT for process2
10 millisec
***********************************************
PROCESS BT WT TAT
0 20 0 20
1 30 0 30
2 10 20 30
***********************************************
Avg waiting time=6.6666665 millisec
42
43RESULT
44 Thus the FCFS program was executed and verified successfully.
AIM
To write a C program to implement the CPU scheduling algorithm for priority.
ALGORITHM
1. Start the program
2.Declare the array size
3. Get the number of process arrival time, execution time and priority
4. Start with the higher priority process from its initial position, let other process
enter the queue
5. Calculate the total waiting time for each process, average waiting time
6. Display the values
7. 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];
printf("Enter the number of process:");
scanf("%d", &n);
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++) {
if (i == 0) {
st[i] = at[i];
wt[i] = st[i] - at[i];
OUTPUT
Enter the number of process:3
Enter process name, arrivaltime, execution time & priority: 1 2 3
Enter process name, arrivaltime, execution time & priority: 1 3 4
Enter process name, arrivaltime, execution time & priority: 5 4 3
Pname arrivaltime executiontime priority waitingtime tatime
1 2 3 1 0 3
2 3 1 3 2 3
4 5 4 3 1 5
Average waiting time is:1.000000 millisec
Average turnaroundtime is:3.666667 millisec
1
2
3
4
5RESULT
Thus the priority program for CPU scheduling algorithms were successfully executed
and verified.
VIVA QUESTIONS:
1. What is CPU Scheduler?
AIM
To write a java program to implement producer consumer relationship using
semaphore.
ALGORITHM
1. The Semaphore mutex, full & empty are initialized.
2. In the case of producer process
i) Produce an item in to temporary variable.
ii) If there is empty space in the buffer check the mutex value for enter into the critical
section.
iii) If the mutex value is 0, allow the producer to add value in the temporary variable
to the buffer.
3. In the case of consumer process
i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the mutex==0, remove
item from buffer
iii) Signal the mutex value and reduce the empty value by 1.
iv) Consume the item.
4. Print the result
PROGRAM
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
Semaphore binary = new Semaphore(1);
public static void main(String args[]) {
final SemaphoreTest test = new SemaphoreTest();
new Thread(){
@Override
public void run(){
test.mutualExclusion();
}
}.start();
new Thread(){
@Override
public void run(){
test.mutualExclusion();
}
}.start();
}
private void mutualExclusion() {
try {
binary.acquire();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
binary.release();
System.out.println(Thread.currentThread().getName() + " outside of mutual exclusive
region");
}
}}
OUTPUT
Thread-0 inside mutual exclusive region
Thread-0 outside of mutual exclusive region
Thread-1 inside mutual exclusive region
Thread-1 outside of mutual exclusive region
RESULT
Thus the program for semaphore was successfully executed and verified.
VIVA QUESTIONS:
1. What is a semaphore?
3. What is a thread?
4. What is a P-thread?
AIM
To write a program for interprocess communication using shared memory.
ALGORITHM
SERVER
1. Define shared memory size of 30 bytes
2. Define the key to be 5600
3. Create a shared memory using shmget () system calls and gets the shared memory
id in variable shmid.
4. Attach the shared memory to server data space
5. Get the content to be placed in the shared memory from the user of the server.
6. Write the content in the shared memory, which will read out by the client.
7. Stop the program
CLIENT
1. Define the key to be 5600
2. Attach the client to the shared memory created by the server.
3. Read the content from the shared memory.
4. Display the content on the screen.
5. Stop the program
PROGRAM
#include<stdio.h>
#include<unistd.h>
#include<string.h>
void main() {
int pid[2], pid1[2], pid2[2], pid3[2], pid4[2];
int a[20], i, l, s = 0;
char str[20];
pipe(pid);
pipe(pid1);
pipe(pid2);
pipe(pid3);
pipe(pid4);
if (fork() == 0) {
sleep(5);
close(pid[1]);
read(pid[0], str, sizeof (str));
for (i = 0, l = 0; str[i] != '\0'; i++)
l = l + 1;
close(pid3[0]);
write(pid3[1], &l, sizeof (l));
sleep(6);
printf("Enter %d array elementz:", l);
for (i = 0; i < l; i++)
scanf("%d", &a[i]);
close(pid1[0]);
write(pid1[1], a, sizeof (a));
close(pid4[0]);
write(pid4[1], &l, sizeof (l));
}
else if (fork() == 0) {
sleep(2);
close(pid1[1]);
close(pid4[1]);
read(pid4[0], &l, sizeof (l));
read(pid1[0], a, sizeof (a));
for (i = 0; i < l; i++)
s = s + a[i];
close(pid2[0]);
write(pid2[1], &s, sizeof (s));
}
else {
printf("\nEnter string:");
scanf("%s", str);
close(pid[0]);
write(pid[1], str, sizeof (str));
sleep(7);
close(pid3[1]);
read(pid3[0], &l, sizeof (l));
printf("\nThe string length=%d", l);
sleep(8);
close(pid2[1]);
read(pid2[0], &s, sizeof (s));
printf("\nSum=%d", s);
}
}
OUTPUT
Enter string:KINGS
Enter 5 array elements:
The string length=5
HELLO
Sum=-2110358802
RESULT
Thus the program for shared memory and IPC was successfully executed
and verified.
VIVA QUESTIONS:
4. Define IPC.
5. What is fork?
AIM
To implement deadlock avoidance by using banker’s algorithm.
ALGORITHM
Safety algorithm
1. Start the program
2. Initialize a temporary vector W (Work) to equal the available vector A.
3. Find an index i (row i) such that
Need i : = W
If no such row exists, the system will deadlock, since no process can run to
completion.
4. If such a row is found, mark this process as finished, and add all its resources to
W Vector i, W = W + Ci
Go to step 2, until either all processes are marked terminated (in this case
initial state is safe), or until a deadlock occurs, in which the state is not safe.
PROGRAM
import java.util.Scanner;
public class Bankers {
int claim[][], alloc[][], av[], need[], p, r, alsum[], sum, temp[][];
int a = 0, b = 0, c;
boolean flag;
Scanner src = new Scanner(System.in);
Bankers(int p, int r) {
this.p = p;
this.r = r;
claim = new int[p][r];
alloc = new int[p][r];
av = new int[r];
KINGS COLLEGE OF ENGINEERING 34
CS8461 OPERATING SYSTEMS LAB
while (b < p) {
flag = false;
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
if (temp[i][0] == 89) {
break;
}
if (temp[i][j] <= need[j]) {
a++;
} else {
break;
}
}
if (a == r) {
System.out.println("Process P" + (i + 1) + " is Completed");
addtoNeed(i);
temp[i][0] = 89;
a = 0;
c++;
flag = true;
}
if (flag == true) {
break;
}
}
b++;
}
}
int r = src.nextInt();
Bankers obj = new Bankers(p, r);
obj.calNeed();
obj.checkNeed();
obj.compareNeed();
}
}
OUTPUT
ENTER THE NO. OF PROCESS
5
ENTER THE NO. OF RESOURCES
3
ENTER THE 3 VALUES IN AVAILABLE VECTOR
3
3
2
ENTER THE CLAIM MATRIX OF5 X 3
0
1
0
2
0
0
3
0
2
2
1
1
0
0
2
ENTER THE ALLOCATION MATRIX OF 5 X 3
7
5
3
3
2
2
9
0
2
2
2
2
4
3
3
Initial Need Vector -22
Initial Need Vector -9
Initial Need Vector -10
RESULT
Thus the program to implement banker’s algorithm for dead lock avoidance was
executed successfully.
VIVA QUESTIONS:
1. What is a deadlock?
AIM
To write a C program to implement deadlock detection algorithm
ALGORITHM
1. Start the process
2. Obtain the processes and resource availability details
3. Resources will be allocated to processes if processes do not compete for same
resource
4. Resource will be released by process if job completes
5. Before job completion if resource is required, process enters into deadlock state
6. Status of resource allocated helps deadlock detection
7. Display the process, resource details
8. Stop the process
PROGRAM
#include<stdio.h>
#include<conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n, r;
void input();
void show();
void cal();
int main() {
int i, j;
printf("********** Deadlock Detection Algo ************\n");
input();
show();
cal();
getch();
return 0;
}
void input() {
int i, j;
printf("Enter the no of Processes\t");
scanf("%d", &n);
printf("Enter the no of resource instances\t");
scanf("%d", &r);
printf("Enter the Max Matrix\n");
for (i = 0; i < n; i++) {
for (j = 0; j < r; j++) {
scanf("%d", &max[i][j]);
}
}
printf("Enter the Allocation Matrix\n");
OUTPUT
********** Deadlock Detection Alg ************
RESULT
Thus the program for deadlock detection was successfully executed and verified.
AIM
To write a program to implement threading and synchronization.
ALGORITHM
1. Create a Bank Database
2. Create functions for adding a new user, depositing the amt, withdrawing the
amt & viewing the customer
3. Create a thread for each functionality
4. Implement the concurrency control among the threads
5. Function - add new user
a. Get the user details namely, Acno, Name & Bank Balance
b. Write the user details to the bank database
6. Function -Deposit
a. Get the Acno & Amt
b. Update the Bank balance for the given Acno
7. Function- Withdraw
a. Get the Acno & Amt
b. Update the Bank balance for the given Acno
8. Function- View
a. Get the Acno
b. Display the account details
PROGRAM
import java.util.*;
public class BankingMain {
public static final int a_maxi = 10; // number of accounts
public static long[] balance = new long[a_maxi];
public static Random r_number;
private static final int t_maxi = 5; // number of threads
private static BankingThread[] t_list = new BankingThread[t_maxi];
private static long t_step;
private static Object o_lock;
private static Object[] a_lock = new Object[a_maxi];
public static void main(String[] a) {
o_lock = new Object();
for (int i = 0; i < a_maxi; i++) {
a_lock[i] = new Object();
}
t_step = 1; // using doTransaction1();
System.out.println("No synchronization:");
testATM();
printResult();
t_step = 2; // using doTransaction2();
System.out.println("Synchronized method:");
testATM();
printResult();
t_step = 3; // using doTransaction3();
System.out.println("Synchronized statements:");
testATM();
printResult();
t_step = 4; // using doTransaction4();
System.out.println("Synchronized statements per account:");
testATM();
printResult();
}
private static void testATM() {
for (int i = 0; i < a_maxi; i++) {
balance[i] = 0;
}
r_number = new Random();
ThreadGroup g = new ThreadGroup("ATM");
for (int i = 0; i < t_maxi; i++) {
BankingThread t = new BankingThread(g, String.valueOf(i));
t.start();
t_list[i] = t;
}
try {
Thread.sleep(5 * 1000); // working period
} catch (InterruptedException e) {
System.out.println("Interrupted in the mainthread.");
}
g.interrupt();
while (g.activeCount() > 0); // wait for all threads to end
}
private static void printResult() {
System.out.print("Account");
for (int i = 0; i < t_maxi; i++) {
System.out.print(", ATM " + i);
}
System.out.print(", Transaction Sum, Balance");
for (int j = 0; j < a_maxi; j++) {
System.out.print("\n" + j);
long sum = 0;
for (int i = 0; i < t_maxi; i++) {
sum += t_list[i].getBalance(j);
System.out.print(", " + getCurrency(t_list[i].getBalance(j)));
}
System.out.print(", " + getCurrency(sum) +
", " + getCurrency(balance[j]));
}
System.out.print("\n# of Transactions");
for (int i = 0; i < t_maxi; i++) {
System.out.print(", " + t_list[i].transactionCount());
}
System.out.print("\n");
}
private static String getCurrency(long d) {
long i = d / 100;
long f = Math.abs(d) % 100;
String fs = String.valueOf(f);
if (f < 10) {
fs = "0" + fs;
}
return String.valueOf(i) + "." + fs;
}
public static long getStep() {
return t_step;
}
try {
Thread.sleep(1); // slow down the process
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // re-set the flag
}
balance[i] = c + a; // set current balance
}
return ok;
}
t_balance[n] += a;
}
}
try {
sleep(10); // wait for the next customer
} catch (InterruptedException e) {
break;
}}} }
OUTPUT
No synchronization:
Account, ATM 0, ATM 1, ATM 2, ATM 3, ATM 4, Trans. Sum, Bal
0, -169.92, -200.43, 43.72, 268.13, 112.82, 54.32, 215.56
RESULT:
Thus the program for threading and synchronization is successfully executed.
VIVA QUESTIONS:
2. What is fragmentation?
temp_a=temp_a->next;
}
}
void display_free(struct free_list *temp_f)
{
printf("\n\n free list:");
printf("\n=================");
while(temp_f!=NULL)
{
printf("\n st_add:%d end_add:%d",temp_f->st_add,
temp_f->end_add);
temp_f=temp_f->next;
}
}
void insert(int p)
{
struct free_list *temp_f;
struct allocate *temp_a,*pre_a;
int i,n;
do
{
srand((unsigned int)time((time_t*)NULL));
n=rand()%5;
}
while(n==0);
printf("\n\n no. of process:%d",n);
for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%300;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{
printf("\n\n process to be inserted:%d size:%d",pro[i].pid,pro[i].size);
temp_f=flist;
temp_a=alot;
while(temp_f!=NULL && temp_f->end_add-temp_f->st_add
< pro[i].size)
{
temp_f=temp_f->next;
}
if(temp_f!=NULL)
{
{
printf("\n\n\n process to be deleted:");
scanf("%d",&ndpid);
temp_a=alot;
temp_f=flist;
while(temp_a!=NULL && temp_a->pid!=ndpid)
{
pre_a=temp_a;
temp_a=temp_a->next;
}
if(temp_a!=NULL)
{
if(alot==temp_a)
alot=temp_a->next;
else
pre_a->next=temp_a->next;
pre_f=NULL;
while(temp_f!=NULL && temp_f->st_add < temp_a->st_add)
{
pre_f=temp_f;
temp_f=temp_f->next;
}
if(pre_f!=NULL && pre_f->end_add==temp_a->st_add)
pre_f->end_add=temp_a->end_add;
else if(pre_f!=NULL&&temp_f!=NULL&&
temp_f- >st_add==temp_a->end_add)
temp_f->st_add=temp_a->st_add;
else
{
free_alot=(struct free_list*)malloc(sizeof
(struct free_list));
free_alot->st_add=temp_a->st_add;
free_alot->end_add=temp_a->end_add;
if(pre_f!=NULL)
pre_f->next=free_alot;
free_alot->next=temp_f;
if(flist==temp_f)
{
flist=free_alot;
}
}
free(temp_a);
}
else printf("\n process not in memory");
temp_f=flist;
while(temp_f!=NULL)
{
if(temp_f->end_add==temp_f->next->st_add)
{
temp_f->end_add=temp_f->next->end_add;
temp_f->next=temp_f->next->next;
}
temp_f=temp_f->next;
}
display_alot(alot);
display_free(flist);
getch();
}
insert(10);
}
OUTPUT:
no. of process:3
process to be inserted:0 size:120
allocated list:
================
process:0 st_add:0 end_add:120
free list:
=================
st_add:120 end_add:1024
process to be inserted:1 size:185
allocated list:
================
process:0 st_add:0 end_add:120
process:1 st_add:120 end_add:305
free list:
=================
st_add:305 end_add:1024
process to be inserted:2 size:246
allocated list:
================
process:0 st_add:0 end_add:120
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
free list:
=================
st_add:551 end_add:1024
no.of process deletion:1
process to be deleted:0
allocated list:
================
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
free list:
=================
st_add:0 end_add:120
st_add:551 end_add:1024
no. of process:3
process to be inserted:10 size:195
allocated list:
================
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
process:10 st_add:551 end_add:746
free list:
=================
st_add:0 end_add:120
st_add:746 end_add:1024
process to be inserted:11 size:96
allocated list:
================
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
process:10 st_add:551 end_add:746
process:11 st_add:0 end_add:96
free list:
=================
st_add:96 end_add:120
st_add:746 end_add:1024
process to be inserted:12 size:148
allocated list:
================
process:1 st_add:120 end_add:305
process:2 st_add:305 end_add:551
process:10 st_add:551 end_add:746
process:11 st_add:0 end_add:96
process:12 st_add:746 end_add:894
free list:
=================
st_add:96 end_add:120
st_add:894 end_add:1024
RESULT:
Thus the program for Implement first fit algorithm for memory management is
written and successfully executed.
EX NO: 9 (a) Implement Best fit algorithm for memory management
AIM :
To write a program for Implement best fit memory management
ALGORITHM:
1.Start the program.
2. Declare the size.
3. Get the number of processes to be inserted.
4. Allocate the best hole that is small enough searching.
while(temp_f!=NULL)
{
printf("\n st_add:%d end_add:%d",temp_f->st_add,
temp_f->end_add);
temp_f=temp_f->next;
}
}
void insert(int p)
{
struct free_list *temp_f;
struct allocate *temp_a,*pre_a;
int i,n;
do
{
srand((unsigned int)time((time_t*)NULL));
n=rand()%10;
}
while(n==0);
printf("\n\n no. of process:%d",n);
for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%550;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{
printf("\n\n process to be inserted:%d size:%d",pro[i].pid,pro[i].size);
temp_f=flist;
temp_a=alot;
while(temp_f!=NULL && temp_f->end_add-temp_f->
st_add < pro[i].size)
{
temp_f=temp_f->next;
}
if(temp_f!=NULL)
{
pre_a=(struct allocate*)malloc(sizeof(struct allocate));
pre_a->st_add=temp_f->st_add;
pre_a->end_add=temp_f->st_add=temp_f->st_add+pro[i].size;
pre_a->pid=pro[i].pid;
if(temp_a==NULL)
{
alot=pre_a;
pre_a->next=NULL;
}
else
{
while(temp_a->next!=NULL)
{
temp_a=temp_a->next;
}
temp_a->next=pre_a;
pre_a->next=NULL;
}
}
else
printf("\n there is not enough space");
display_alot(alot);
display_free(flist);
getch();
}
}
void bestfit(int p)
{
struct free_list *temp_f,*enough_hole;
struct allocate *temp_a,*pre_a;
int i,n,rem_space;
do
{
srand((unsigned int)time((time_t*)NULL));
n=rand()%10;
}
while(n==0);
printf("\n no of processes:%d",n);
for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%200;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{
printf("\n process to be inserted:%d size:%d",pro[i].pid,pro[i].size);
temp_f=flist;
temp_a=alot;
enough_hole=NULL;
rem_space=1024;
while(temp_f!=NULL)
{
if(temp_f->end_add - temp_f->st_add >= pro[i].size)
{
if(temp_f->end_add - temp_f->
st_add - pro[i].size<rem_space)
{
rem_space=temp_f->end_add - temp_f->
st_add - pro[i].size;
enough_hole=temp_f;
}
}
temp_f=temp_f->next;
}
if(enough_hole!=NULL)
{
pre_a=(struct allocate*)malloc(sizeof(struct allocate));
pre_a->st_add=enough_hole->st_add;
pre_a->end_add=enough_hole->st_add=
enough_hole->st_add + pro[i].size;
pre_a->pid=pro[i].pid;
if(temp_a==NULL)
{
alot=pre_a;
pre_a->next=NULL;
}
else
{
while(temp_1->next!=NULL)
{
temp_a=temp_a->next;
}
temp_a->next=pre_a;
pre_a->next=NULL;
}
}
else
printf("\n there is not enough space");
display_alot(alot);
display_free(flist);
getch();
}
}
void main()
{
int no,n,i,nod,ndpid;
struct process pro[10];
(struct free_list));
free_alot->st_add=temp_a->st_add;
free_alot->end_add=temp_a->end_add;
if(pre_f!=NULL)
pre_f->next=free_alot;
free_alot->next=temp_f;
if(flist==temp_f)
{
flist=free_alot;
}
}
free(temp_a);
}
else printf("\n process not in memory");
temp_f=flist;
while(temp_f!=NULL)
{
if(temp_f->end_add==temp_f->next->st_add)
{
temp_f->end_add=temp_f->next->end_add;
temp_f->next=temp_f->next->next;
}
temp_f=temp_f->next;
}
display_alot(alot);
display_free(flist);
getch();
}
bestfit(10);
}
OUTPUT:
no. of process:7
process to be inserted:0 size:351
allocated list:
================
process:0 st_add:0 end_add:351
free list:
=================
st_add:351 end_add:1024
process to be inserted:1 size:466
allocated list:
================
process:0 st_add:0 end_add:351
process:1 st_add:351 end_add:817
free list:
=================
st_add:817 end_add:1024
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:0 end_add:351
st_add:906 end_add:1024
process to be deleted:2
process not in memory
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:0 end_add:351
st_add:906 end_add:1024
process to be deleted:3
process not in memory
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:0 end_add:351
st_add:906 end_add:1024
process to be deleted:4
process not in memory
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
free list:
=================
st_add:0 end_add:351
st_add:906 end_add:1024
no of processes:9
process to be inserted:10 size:155
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
free list:
=================
st_add:155 end_add:351
st_add:906 end_add:1024
process to be inserted:11 size:43
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
free list:
=================
st_add:155 end_add:351
st_add:949 end_add:1024
process to be inserted:12 size:188
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
free list:
=================
st_add:343 end_add:351
st_add:949 end_add:1024
process to be inserted:13 size:7
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
process:13 st_add:343 end_add:350
free list:
=================
st_add:350 end_add:351
st_add:949 end_add:1024
process to be inserted:14 size:160
there is not enough space
allocated list:
================
process:1 st_add:351 end_add:817
process:6 st_add:817 end_add:906
process:10 st_add:0 end_add:155
process:11 st_add:906 end_add:949
process:12 st_add:155 end_add:343
for(i=0;i<n;i++)
{
pro[i].pid=i+p;
do
{
pro[i].size=rand()%250;
}
while(pro[i].size==0);
}
for(i=0;i<n;i++)
{
printf("\n process to be inserted: %d size :%d",pro[i].pid,pro[i].size);
temp_f=flist;
temp_a=alot;
big_hole=NULL;
while(temp_f!=NULL)
{
if(temp_f->end_add-temp_f->st_add>=pro[i].size)
{
if(big_hole==NULL)
big_hole=temp_f;
else if(temp_f->end_add - temp_f->st_add > big_hole
-> end_add - big_hole-> st_add)
big_hole=temp_f;
}
temp_f=temp_f->next;
}
if(big_hole!= NULL)
{
pre_a=(struct allocate*) malloc (sizeof(struct allocate));
pre_a->st_add=big_hole->st_add;
pre_a->end_add=big_hole->st_add=big_hole->st_add + pro[i].size;
pre_a->pid=pro[i].pid;
if(temp_a==NULL)
{
alot=pre_a;
pre_a->next=NULL;
}
else
{
while(temp_a->next!=NULL)
temp_a=temp_a->next;
temp_a->next= pre_a;
pre_a->next=NULL;
}
}
else
temp_f=temp_f->next;
}
if(pre_f!=NULL && pre_f->end_add==temp_a->st_add)
pre_f->end_add=temp_a->end_add;
else if(pre_f!=NULL&&temp_f!=NULL&&
temp_f->st_add==temp_a->end_add)
temp_f->st_add=temp_a->st_add;
else
{
free_alot=(struct free_list*)malloc(sizeof(struct free_list));
free_alot->st_add=temp_a->st_add;
free_alot->end_add=temp_a->end_add;
if(pre_f!=NULL)
pre_f->next=free_alot;
free_alot->next=temp_f;
if(flist==temp_f)
{
flist=free_alot;
}
}
free(temp_a);
}
else printf("\n process not in memory");
temp_f=flist;
while(temp_f!=NULL)
{
if(temp_f->end_add==temp_f->next->st_add)
{
temp_f->end_add=temp_f->next->end_add;
temp_f->next=temp_f->next->next;
}
temp_f=temp_f->next;
}
display_alot(alot);
display_free(flist);
getch();
}
worstfit(10);
}
OUTPUT:
no. of process:9
process to be inserted:0 size:21
allocated list:
================
process:0 st_add:0 end_add:21
free list:
=================
st_add:21 end_add:1024
process to be inserted:1 size:469
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
free list:
=================
st_add:490 end_add:1024
process to be inserted:2 size:30
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
free list:
=================
st_add:520 end_add:1024
process to be inserted:3 size:74
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
free list:
=================
st_add:594 end_add:1024
process to be inserted:4 size:182
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
free list:
=================
st_add:776 end_add:1024
process to be inserted:5 size:100
allocated list:
================
process:0 st_add:0 end_add:21
process:1 st_add:21 end_add:490
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
process:11 st_add:105 end_add:198
process:12 st_add:198 end_add:258
free list:
=================
st_add:258 end_add:490
st_add:876 end_add:1024
process to be inserted: 13 size :103
allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
process:11 st_add:105 end_add:198
process:12 st_add:198 end_add:258
process:13 st_add:258 end_add:361
free list:
=================
st_add:361 end_add:490
st_add:876 end_add:1024
process to be inserted: 14 size :72
allocated list:
================
process:2 st_add:490 end_add:520
process:3 st_add:520 end_add:594
process:4 st_add:594 end_add:776
process:5 st_add:776 end_add:876
process:10 st_add:0 end_add:105
process:11 st_add:105 end_add:198
process:12 st_add:198 end_add:258 process:13 st_add:258 end_add:361 process:14
st_add:876 end_add:948
free list:
=================
st_add:361 end_add:490
st_add:948 end_add:1024
process to be inserted: 15 size :17
allocated list:
================
process:2 st_add:490 end_add:520
AIM
To write a program to implement first fit algorithm for memory management.
ALGORITHM
1. Start the process
2. Declare the size
3. Get the number of processes to be inserted
4. Allocate the first hole that is big enough
5. Display the values
6. Stop the process
PROGRAM
import java.io.DataInputStream;
import java.io.IOException;
public class FirstFit {
public static void main(String args[]) throws IOException {
int n, i, it;
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter Number of Holes");
n = Integer.parseInt(in.readLine());
int sp[] = new int[n];
for (i = 0; i < n; i++) {
System.out.println("Enter size of Hole" + (i + 1));
sp[i] = Integer.parseInt(in.readLine());
}
System.out.println("Before Insertion of new process");
System.out.println("hole\t\tsize");
for (i = 0; i < n; i++) {
System.out.println("hole" + (i + 1) + "\t\t" + sp[i]);
}
System.out.println("enter new process size to insert");
it = Integer.parseInt(in.readLine());
for (i = 0; i < n; i++) {
if (it < sp[i]) {
sp[i] = sp[i] - it;
break;
}
}
System.out.println("After Insertion of new process");
System.out.println("hole\t\tsize");
for (i = 0; i < n; i++) {
System.out.println("hole" + (i + 1) + "\t\t" + sp[i]);
}
}
}
OUTPUT
Enter Number of Holes
2
Enter size of Hole1
1
Enter size of Hole2
2
Before Insertion of new process
hole size
hole1 1
hole2 2
enter new process size to insert
2
After Insertion of new process
hole size
hole1 1
hole2 2
RESULT
Thus the program for first fit algorithm for memory management was executed and
verified.
AIM
To write a program to implement next fit algorithm for memory management.
ALGORITHM
1. Start the program.
2. Get the number of segments and size.
3. Get the memory requirement and select the option.
4. If the option is ‘1’ call next fit function.
5. Otherwise exit.
6. For first fit, allocate the process to first possible segment which is free.
7. For next fit, do the following steps.
8. Sorts the segments according to their sizes.
9. Allocate the process to the segment which is equal to or slightly greater than the
process size.
10. Stop the program.
PROGRAM
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class NextFit {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int nh, np;
System.out.println("Enter the number of Holes:");
nh = Integer.parseInt(br.readLine());
System.out.println("Enter the number of Processes:");
np = Integer.parseInt(br.readLine());
int P[] = new int[np];
int H[] = new int[nh];
System.out.println("Enter the size of holes:");
for (int i = 0; i < nh; i++) {
System.out.print("H[" + i + "]=");
H[i] = Integer.parseInt(br.readLine());
System.out.println();
}
System.out.println("Enter the size of Processes:");
for (int i = 0; i < np; i++) {
System.out.print("P[" + i + "]=");
P[i] = Integer.parseInt(br.readLine());
System.out.println();
}
int h = nh;
int j = 0;
while (h > 0) {
for (int i = 0; i < nh; i++) {
if (H[i] > P[j]) {
System.out.println("Process " + j + "allocated in hole " + i);
H[i] -= P[j];
j++;
h--;
}
}
}
System.out.println("_______________");
}
}
OUTPUT
Enter the number of Holes:
2
Enter the number of Processes:
3
Enter the size of holes:
H[0]=2
H[1]=3
Enter the size of Processes:
P[0]=2
P[1]=3
P[2]=3
Process 0 allocated in hole 1
RESULT
Thus the program for next fit algorithm for memory management was executed and
verified.
AIM
To write a program to implement best fit algorithm for memory management.
ALGORITHM
1. Start the program
2. Declare the size
3. Get the number of processes to be inserted
4. Allocate the best hole that is small enough searching
5. Start at the best of the set of holes
6. Compare the hole in the list
7. If small enough, then stop searching in the procedure
8. Display the values
9. Stop the program
PROGRAM
import java.io.DataInputStream;
import java.io.IOException;
public class best {
public static void main(String args[]) throws IOException {
int flag[] = new int[10];
int sm[] = new int[10];
int i, sr, nm;
int sp, loc = 0;
int cntrl = 1000;
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter the no of memory segments\n");
nm = Integer.parseInt(in.readLine());
System.out.println("Enter the size of memory segments\n");
if (flag[i] == 0) {
sp = sm[i];
if (sr <= sp) {
if (cntrl > sp) {
cntrl = sp;
loc = i;
}
}
}
}
if (cntrl == 0) {
System.out.println("\n Space not available");
} else {
sm[loc] = sr;
flag[loc] = 1;
}
System.out.println("\nAfter Bestfit Allocation\n");
System.out.println("Index \t\t Memory Segment\n");
for (i = 0; i < nm; i++) {
System.out.println((i + 1) + "\t\t" + sm[i]);
}
System.out.println("\n The process allocated to the memory segments " + (loc +
1));
}
}
OUTPUT
Enter the no of memory segments
3
Enter the size of memory segments
2
1
2
Before best fit allocation
Index Memory Segments
1 2
2 1
3 2
RESULT
Thus the best fit program for paging techniques was successfully executed
and verified.
VIVA QUESTIONS:
1. What are the common strategies to select a free hole from a set of available
holes?
AIM
To write a c program to implement FIFO (First In First Out) page replacement
algorithm
ALGORITHM
1. Start the program
2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Form a queue to hold all pages
6. Insert the page required memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted
9. Display the values
10. Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
clrscr();
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;
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);
getch();
return 0;
}
OUTPUT
RESULT
Thus the FIFO program was successfully executed and verified.
AIM
To write a c program to implement LRU (Least Recently Used) page replacement
algorithm
ALGORITHM
1. Start the program
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
clrscr();
printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);
}
printf("\n");
}
}
}
printf("\nThe no. of page faults is %d",c);
getch();
return 0;
OUTPUT
Enter no. of pages: 3
Enter the reference string: Adithya
Enter no of frames: 1627902152
The no. of page faults is 3
RESULT
Thus the LRU program was successfully executed and verified.
AIM
To write a C program for page replacement LFU (Least Frequently Used) algorithm.
ALGORITHM
1. Start the program
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least frequently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the program
PROGRAM
#include<stdio.h>
int main() {
int f, p;
int pages[50], frame[10], hit = 0, count[50], time[50];
int i, j, page, flag, least, minTime, temp;
flag = 0;
frame[j] = pages[i];
break;
}
if (count[least] > count[frame[j]]) {
least = frame[j];
}
}
if (flag) {
minTime = 50;
for (j = 0; j < f; j++) {
if (count[frame[j]] == count[least] && time[frame[j]] < minTime) {
temp = j;
minTime = time[frame[j]];
}
}
count[frame[temp]] = 0;
frame[temp] = pages[i];
}
for (j = 0; j < f; j++) {
printf("%d ", frame[j]);
}
printf("\n");
}
printf("Page hit = %d", hit);
return 0;
}
OUTPUT
Enter no of frames : 3
Enter no of pages: 2
Enter page number :
1
2
1 -1 -1
1 2 -1
Page hit = 0
RESULT
Thus the LFU program was successfully executed and verified.
VIVA QUESTIONS:
3. What is cache-coherency?
AIM
To write a C program to implement file organization concept using the technique
single level directory.
ALGORITHM
1. Start the program
2. Declare the number, names and size of the directories and file names
3. Get the values for the declared variables
4. Display the files that are available in the directories
5. Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
{
int master,s[20];
char f[20][20][20];
char d[20][20];
int i,j;
clrscr();
printf("enter number of directories:");
scanf("%d",&master);
printf("enter names of directories:");
for(i=0;i<master;i++)
scanf("%s",&d[i]);
printf("enter size of directories:");
for(i=0;i<master;i++)
scanf("%d",&s[i]);
printf("enter the file names :");
for(i=0;i<master;i++)
for(j=0;j<s[i];j++)
scanf("%s",&f[i][j]);
printf("\n");
printf(" directory\tsize\tfilenames\n");
printf("*************************************************\n");
for(i=0;i<master;i++)
{
printf("%s\t\t%2d\t",d[i],s[i]);
for(j=0;j<s[i];j++)
printf("%s\n\t\t\t",f[i][j]);
printf("\n");
}
printf("\t\n");
getch();
}
OUTPUT
Enter number of directories:2
Enter names of directories:a1
Enter size of directories:2
Enter the file names:
b1
b2
Welcome to all
Directory size filenames
************************************
a1 2 b1
b2
a2 2 welcome to all
RESULT
Thus the single level directory program was successfully executed and verified.
AIM
To write a C program to implement file organization concept using the two level
directory.
ALGORITHM
1. Start the program
2. Declare the number, names and size of the directories and subdirectories and file
names.
3. Get the values for the declared variables.
4. Display the files that are available in the directories and subdirectories.
5. Stop the program
PROGRAM
#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k;
char f[30], d[30];
clrscr();
dcnt=0;
while(1)
{
printf("\n\n1. Create Directory\t2. Create File\t3. Delete File");
printf("\n4. Search File\t\t5. Display\t6. Exit\t
Enter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter name of directory -- ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",dir[i].fname[dir[i].fcnt]);
dir[i].fcnt++;
printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d);
break;
case 3: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is deleted ",f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found",f);
goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
case 4: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is found ",f);
goto jmp1;
}
}
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display
6. Exit
Enter your choice -- 1
Directory created
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display
6. Exit
Enter your choice -- 1
Enter name of directory -- DIR2
Directory created
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display
6. Exit
Enter your choice -- 2
Enter name of the directory – DIR1
Enter name of the file -- A1
File created
RESULT
Thus the two level directory program was executed and verified successfully.
AIM
To write a C program to implement file organization concept using the hierarchical
level directory.
ALGORITHM
1. Start the program
2. Declare the number, names and size of the directories and subdirectories and file
names.
3. Get the values for the declared variables by maintaining their root directory details
4. Display the files that are available in the directories and subdirectories.
5. Stop the program
PROGRAM
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element
node; void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\\tc\\BGI");
display(root);
getch();
closegraph();
}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("Enter name of dir/file(under %s) :
",dname); fflush(stdin);
gets((*root)->name);
printf("enter 1 for Dir/2 for
file :"); scanf("%d",&(*root)->ftype); (*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
KINGS COLLEGE OF ENGINEERING
101
CS8461 OPERATING SYSTEMS LAB
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("No of sub directories/files(for %s):",(*root)->name); scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else gap=(rx-lx)/(*root)->nc; for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]),lev+1,(*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else (*root)->nc=0;
}}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14); if(root
!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1) bar3d(root->x-20,root->y-
10,root->x+20,root->y+10,0,0); else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
}
OUTPUT:
Enter Name of dir/file(under root): ROOT
Enter 1 for Dir//2 for File: 1 No of subdirectories/files(for USER1): 1
Enter Name of dir/file(under USER1): SUBDIR1
KINGS COLLEGE OF ENGINEERING
102
CS8461 OPERATING SYSTEMS LAB
RESULT
Thus the hierarchical level directory program was executed and verified successfully.
AIM
KINGS COLLEGE OF ENGINEERING
103
CS8461 OPERATING SYSTEMS LAB
ALGORITHM
1. Start the program
2. Read the root directory and sub directory details
3. Read the common file to be shared between directories
4. Establish link for the file for the directories
5. Updation on the file will reflect on both the directories
6. Display the directory and file details
5. Stop the program.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<string.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element
node; typedef struct
{
char from[20];
char to[20];
}link; link
L[10]; int
nofl;
node * root;
void main()
{
int gd=DETECT,gm;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
read_links();
clrscr();
initgraph(&gd,&gm,"c:\\tc\\BGI");
draw_link_lines();
display(root);
getch();
closegraph();
}
read_links()
{
KINGS COLLEGE OF ENGINEERING
104
CS8461 OPERATING SYSTEMS LAB
int i;
printf("how many links");
scanf("%d",&nofl);
for(i=0;i<nofl;i++)
{
printf("File/dir:");
fflush(stdin);
gets(L[i].from);
printf("user name:");
fflush(stdin);
gets(L[i].to);
}
}
draw_link_lines()
{
int i,x1,y1,x2,y2;
for(i=0;i<nofl;i++)
{
search(root,L[i].from,&x1,&y1);
search(root,L[i].to,&x2,&y2);
setcolor(LIGHTGREEN);
setlinestyle(3,0,1);
line(x1,y1,x2,y2);
setcolor(YELLOW);
setlinestyle(0,0,1);
}
}s
earch(node *root,char *s,int *x,int *y)
{
int i;
if(root!=NULL)
{
if(strcmpi(root->name,s)==0)
{
*x=root->x;
*y=root->y;
return;
}
else
{
for(i=0;i<root->nc;i++)
search(root->link[i],s,x,y);
}
}
} create(node **root,int lev,char *
dname,int lx,int rx,int x)
{
KINGS COLLEGE OF ENGINEERING
105
CS8461 OPERATING SYSTEMS LAB
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("enter name of dir/file(under%s):",dname);
fflush(stdin);
gets((*root)->name);
printf("enter 1 for dir/ 2 for
file:"); scanf("%d",&(*root)->ftype); (*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("no of sub directories /files (for %s):",(*root)->name); scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create( & ( (*root)->link[i] ) , lev+1 ,
(*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}
}
/* displays the constructed tree in graphics
mode */
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14); if(root
!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1) bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
KINGS COLLEGE OF ENGINEERING
106
CS8461 OPERATING SYSTEMS LAB
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name); for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
}
OUTPUT
Enter number of directories:1
Enter directory1 names:a1
Enter size of directories:2
Enter subdirectory name and size:b1
Enter file name:a11
Enter file name:a12
Enter subdirectory name and size:c1
Enter file name:b11
Dir name size subdirname size files
**************************************************************************************
a1 2 b1 2 a11
a1 2 c1 1 b11
RESULT
Thus the program for implementation of DAG was successfully executed and verified
VIVA QUESTIONS
2. When designing the file structure for an operating system, what attributes are
considered?
3. What is Sector?
AIM
To write a C program to implement sequential file allocation method.
ALGORITHM
1. Start the program
2. Declare the starting block number and the length of the file
3. Get the starting block number and length of the file from the user
4. Allocate files sequentially until end of the file
5. Display the fragments of the file
6. Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<process.h>
struct sequence {
char n[20];
int i;
} s[20];
int create(int);
int del(int);
void
display(int);
void main() {
int
x = 0, j = 0;
clrscr();
while (1) {
printf("1.creation\n2.delete\n3.display\n4.exit");
printf("\nenter the option");
scanf("%d", &x);
switch (x) {
case 1:
j = create(j
);
break;
case 2:
j = del(j);
break;
case 3: display(j);
break;
case 4: exit(1);
default: printf("wrong option");
KINGS COLLEGE OF ENGINEERING
109
CS8461 OPERATING SYSTEMS LAB
}
}
}
int create(int j) {
int m, v;
j++;
w:
printf("\nenter the file name:");
scanf("%s", &s[j].n);
m = 1;
while (m < j) {
v = strcmp(s[j].n, s[m].n);
if (v == 0) {
printf("file is already exist\nplease enter another name");
goto w;
}
m++;
}
printf("\nenter field:");
scanf("%d", &s[j].i);
return (j);
}
int del(int j) {
j--;
return (j);
}
void display(int j) {
int l;
printf("filename\tfield");
for (l = 1; l <= j; l++)
printf("\n%s\t\t%d\n", s[l].n, s[l].i);
}
OUTPUT
1. creation
2. delete
3. display
4. exit
enter the option
1
enter the file name: kk
enter field:1
1.creation
2.delete
3.display
4.exit
enter the option
3
filename field
kk 1
1.creation
2.delete
3.display
4.exit
enter one option
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25RESULT
Thus the sequential file allocation program was executed and verified.
AIM
To write a C program to implement file allocation concept using indexed allocation
technique.
ALGORITHM
1. Start the program
2. Declare the index block number and total number of files in a block
3. Get the index block number and total number of files in a block from the user
4. Allocate files based on the index block number
5. Arrange the files based on indexes which are created for each fragment of the file
such that each and every similar indexed file is maintained by the primary index to
provide the flow to file fragments.
6. Stop the program
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct file {
char n[20];
int fld, ind;
} s[20];
int no, i = -1, a, b, f, j = -1, fe, t;
char tem[20];
void create();
void display();
void del();
void main() {
clrscr();
while (1) {
printf("\n\n menu");
printf("\n1.create\n2.display\n3.delete\n4.exit");
printf("enter ur choice:");
scanf("%d", &no);
switch (no) {
case 1: create();
break;
case 2: display();
break;
case 3: del();
break;
case 4: exit(0);
default: printf("wrong choice");
}}
}
void create() {
KINGS COLLEGE OF ENGINEERING
112
CS8461 OPERATING SYSTEMS LAB
i++;
printf("\nenter the name of the recorded:");
scanf("%s", &s[i].n);
printf("\nenter the indexno:");
scanf("%d", &s[i].ind);
printf("\nenter the field no:");
scanf("%d", &s[i].fld);
j++;
}
void display() {
for (a = 0; a < i; a++) {
for (b = 0; b < i; b++) {
if (s[b].ind > s[b + 1].ind) {
t = s[b].ind;
s[b].ind = s[b + 1].ind;
s[b + 1].ind = t;
strcpy(tem, s[b].n);
strcpy(s[b].n, s[b + 1].n);
strcpy(s[b + 1].n, tem);
t = s[b].fld;
s[b].fld = s[b + 1].fld;
s[b + 1].fld = t;
} else
continue;
}}
printf("\n ---------------------------------");
printf("\n\t Index Recordname FieldNo");
for (i = 0; i <= j; i++) {
printf("\n\t%d\t", s[i].ind);
printf("\t%s", s[i].n);
printf("\t%d", s[i].fld);
}
i--;
printf("\n -----------------------------------\n");
}
void del() {
int de, index = -
1, k = 0, l;
if (i != -1) {
printf("enter index no to be deleted");
scanf("%d", &de);
index = de;
while (s[k].ind != de) {
k++;
printf("\n\t\t\t%d", k);
}
for (l = k; l <= j; l++)
KINGS COLLEGE OF ENGINEERING
113
CS8461 OPERATING SYSTEMS LAB
AIM
To write a C program to implement file allocation concept using the linked list
technique.
ALGORITHM
1. Create a queue to hold all pages in memory
2. When the page is required, replace the page at the head of the queue
3. Now, the new page is inserted at the tail of the queue
4. Create a stack
5. When the page fault occurs replace page present at the bottom of the stack
6. Stop the allocation
PROGRAM
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int bno, flag, next;
} block;
block b[200], b1;
void main() {
int rnum();
int i, n, s, s1, p[30], r, k[20];
clrscr();
printf("\nEnter number of programs:");
scanf("%d", &n);
printf("\nEnter the memory block request");
for (i = 1; i <= n; i++) {
printf("\nEnter program requirement");
scanf("%d", &p[i]);
}
for (i = 1; i <= n; i++) {
s = rnum();
b[s].bno = 0;
b[s].flag = 1;
k[i] = 0;
r = p[i] - 1;
while (r != 0) {
s1 = rnum();
b[s].next = s1;
b[s1].flag = 1;
b[s1].bno = 0;
s = s1;
r = r - 1;
}
b[s1].next = NULL;
KINGS COLLEGE OF ENGINEERING
115
CS8461 OPERATING SYSTEMS LAB
}
printf("\n Starting blocks for program");
for (i = 1; i <= n; i++)
printf("\n%5d%5d", i, k[i]);
printf("\n allocated blocks");
for (i = 1; i <= 200; i++) {
if (b[i].flag == 1)
printf("\n%5d%5d", b[i].bno, b[i].next);
}
}
int rnum() {
int k, i;
for (i = 1; i <= 200; i++) {
k = rand() % 200;
if (b[i].flag != 1)
break;
}
return k;
}
OUTPUT
Enter number of programs: 2
Enter the memory block request
Enter program requirement 10 20
Enter program requirement
Starting blocks for program
1 0
2 0
allocated blocks
0 149
0 105
0 172
0 119
0 129
0 180
0 108
0 108
0 193
RESULT
Thus the linked file allocation program was executed and verified successfully.
1. What is a reference string?
VIVA QUESTIONS:
2. What is a file?
1
2
3. List out the
3 various file attributes.
4. What is Directory?