Os Lab Record Final
Os Lab Record Final
COLLEGE OF ENGINEERING
Ayikudy, Tenkasi-627852.
Name:
Register Number:
Certified that this record has been submitted for the practical examination held on
at J. P. COLLEGE OF ENGINEERING, Ayikudy conducted by Anna University, Chennai.
AIM :
To perform a case study by installing and exploring various types of operating
windows installation.
1
2. Find the Boot option in the setup utility. Its location depends on your BIOS.
Select the Boot option from the menu, you can now see the options Hard Drive, CD-ROM
Drive, Removable Devices Disk etc.
3. Change the boot sequence setting so that the CD-ROM is first. See the list of “Item Specific
Help” in right side of the window and find keys which is used to toggle to change the boot
sequence.
In a few minutes installation wizard will be started. Select your language and click the
"Install Ubuntu" button to continue...
2
Optionally, you can choose to download updates while installing and/or install third party
software, such as MP3 support. Be aware, though, that if you select those options, the entire
installation process will be longer!
Since we are going to create partitions manually, select Something else, then click
Continue. Keep in mind that even if you do not want to create partitions manually, it is better to
select the same option as indicated here. This would insure that the installer will not overwrite your
Windows , which will destroy your data. The assumption here is that sdb will be used just for
Ubuntu 12.04, and that there are no valuable data on it.
3
Where are you? Select your location and Click the "Continue" button.
Keyboard layout
Select your keyboard layout and UK (English) and Click on “Continue” button.
4
Now Ubuntu 12.04 LTS (Precise Pangolin) operating system will be installed.
5
Please remove the CD and press the "Enter" key to reboot. The computer will be restarted.
In a few seconds, you should see Windows 7′s boot menu with two entires listed – Windows 7 and
Ubuntu 12.04 (LTS).
Then you may choose to boot into Windows 7 or Ubuntu 12.04 using the UP/Down arrow key.
Please select Ubuntu 12.04 (LTS) and press Enter to boot the machine in Ubuntu 12.04
Linux.
6
Here you can see the users on the machine, Click on the user name and enter the password and
press Enter key to login.
7
ii. Procedure for Windows 10 installation :
8
3. Enter the product key to activate Windows and press “Next”, or press“Skip” to enter a valid
product key later.
4. Check the box next to “I accept the license terms” and select “Next”.
9
6. Select the “Load driver” option to load the appropriate driver for the storagedevice.
7. Make sure to load the appropriate storage device driver onto a CD, DVD,or USB flash
drive before completing the next step.
- For storages devices attached to the Intel storage controller, load the Intel Rapid
Storage Technology enterprise (RSTe) driver.
o Select “Browse”, and browse to the CD, DVD, or USB flash drive to where
thestorage device driver is located and select “OK”.
10
[Type here]
- For storages devices attached to the Broadcom controller, load the Broadcom
storagedriver.
o Select “Browse”, browse to the CD, DVD, or USB flash drive to where
thestorage device driver is located and select “OK”.
11
[Type here]
9. Select the drive to install Windows and select “Next” at the bottom.
11. After the installation completes, the system will automatically reboot. If noproduct key
was entered above, then it’ll prompt to enter a product key again. Either enter the
product key here and select “Next” or select “Do this later” at the bottom left.
12
12. Select “Use Express Settings” at the bottom right to use the default settings
or select “Customize settings” at the bottom left. For instructional
purposes, “Use Express settings” was selected.
13
15. At this point, download and install the appropriate device drivers,
i.e. Intel Chipset, Intel AMT, Ethernet, Graphics, etc.
16. Restart the system after installation.
RESULT :
The installation of the Windows Operating System was completed successfully.
14
EX.NO: 2 BASICS OF UNIX COMMANDS
DATE :
AIM :
COMMANDS:
1. DIRECTORY RELATED COMMANDS :
a. MKDIR Command :
Syntax : $pwd
c.CD Command :
d.RMDIR Command :
a. CREATE A FILE :
Syntax :
b.DISPLAY A FILE :
To display the content of file mentioned we use CAT command without „>‟ operator.
Syntax :
15
$cat <filename>.
c.COPYING CONTENTS :
To copy the contents from source to destination file . so that both contents are same.
Syntax :
d.SORTING A FILE :
Syntax :
e.MOVE Command :
To completely move the contents from source file to destination file and to remove the
source file.
Syntax :
f.REMOVE Command :
Syntax :
$rm <filename>
16
3. LIST Command :
If the command does not contain any argument means it is working in the Current
directory.
Options :
4.WORD Command :
$wc <filename>
Options :
-c – to display no of characters.
17
5.PAGE Command :
This command is used to display the contents of the file page wise & next page can beviewed
Syntax :
$pg <filename>
Syntax: $head<filename>
TAIL : This command is used to display the last ten lines of file.
Syntax: $tail<filename>
MORE : It also displays the file page by page .To continue scrolling with more command ,
Syntax: $more<filename>
7.GREP :This command is used to search and print the specified patterns from the file.
9.PIPE : It is a mechanism by which the output of one command can be channeled into the
input
of another command.
18
10. DATE Command :
This command is used to display the current data and time. Syntax :
$date
$date +%ch
Options : -
a = Abbrevated weekday.
A = Full weekday.
b = Abbrevated month.
B = Full month.
M = Minute.
P = Display AM or
PMS = Seconds
T = HH:MM:SS
year.
Z = Time zone .
19
Syntax :
$date „+%H-%M-%S‟
This command is used to display the calendar of the year or the particular month of calendar
year.
Syntax:
$cal <year>
12.Echo Command :
To have the output in the same line , the following commands can be used.
To have the output in different line, the following command can be used.
>line2
>line3”
It is used to display who are the users connected to our computer currently.
Options : -
20
H–Display the output with headers.
b–Display the last booting date or time or when the system was lastly rebooted.
Syntax : $who am i
’tty’ Command :
Syntax : $tty
Syntax :
$bc operations
^d
’CLEAR’ Command :
Syntax : $clear
’MAN’ Command :
It help us to know about the particular command and its options & working. It is like
21
OUTPUT :
cal command:
[oscse18@localhost ~]$ cal
January 2011
Su Mo Tu We Th Fr
Sa1
234 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Date command:
[oscse18@localhost ~]$ date
Wed Jan 12 10:32:11 IST 2011
[oscse18@localhost ~]$ date +%d
12
[oscse18@localhost ~]$ date +%m
01
[oscse18@localhost ~]$ date +%h
Jan
[oscse18@localhost ~]$ date +%y
11
Who command:
[oscse18@localhost ~]$ who root
:0 2011-01-12 09:55
oscse10 pts/6 2011-01-12 10:26 (192.168.0.52)
oscse09 pts/8 2011-01-12 10:27 (192.168.0.53)
oscse01 pts/11 2011-01-12 10:27 (192.168.0.56)
oscse08 pts/10 2011-01-12 10:27 (192.168.0.54)
oscse06 pts/4 2011-01-12 10:27 (192.168.0.60)
oscse03 pts/13 2011-01-12 10:27 (192.168.0.58)
oscse19 pts/3 2011-01-12 10:28 (192.168.0.46)
23
. .. college home stud student
[oscse18@localhost muthu]$ ls -l
total 32
-rw-r--r-- 1 oscse18 oscse 18 Jan 12 11:40 college
-rw-r--r-- 1 oscse18 oscse 21 Jan 12 11:41 home
-rw-r--r-- 1 oscse18 oscse 26 Jan 12 11:31 stud
-rw-r--r-- 1 oscse18 oscse 24 Jan 12 11:11 student
[oscse18@localhost muthu]$ ls -r
student stud home college
Tail command:
[oscse18@localhost muthu]$ tail -2 student
marks
grade
Password command:
[oscse18@localhost muthu]$ pwd
/home/oscse18/muthu
Move command:
[oscse18@localhost muthu]$ mv college home
[oscse18@localhost muthu]$ cat home
muthu usha
geetha
[oscse18@localhost muthu]$ cat college
cat: college: No such file or directory
Grep command:
[oscse18@localhost muthu]$ grep -c ha home
2
RESULT:
24
EX.NO: 3(A) SYSTEM CALLS OF UNIX OPERATING SYSTEMS
DATE :
AIM:
To write a program for system calls of UNIX operating systems (opendir, readdir, closedir)
ALGORITHM :
1. Start the program.
2. Create struct dirent.
3. Declare the variable buff and pointer dptr.
4. Get the directory name.
5. Open the directory.
6. Read the contents in directory and print it.
7. Close the directory.
PROGRAM:
#include<stdio.h>
#include<dirent.h>
struct dirent *dptr;
int main(int argc, char *argv[])
{
char buff[100];
DIR *dirp;
printf(“\n\n ENTER DIRECTORY NAME”);
scanf(“%s”, buff); if((dirp=opendir(buff))==NULL)
{
printf(“The given directory does not exist”);
exit(1);
}
while(dptr=readdir(dirp))
{
printf(“%s\n”,dptr->d_name);
}
closedir(dirp);
}
25
OUTPUT:
cc opdir.c
./a.out
Enter the directory name UNIT
Chap1.c
Chap2.c
RESULT:
Thus a program for system calls of UNIX operating systems (opendir, readdir, closedir) was
written and executed successfully.
26
EX.NO: 3(B) SYSTEM CALLS OF UNIX OPERATING SYSTEMS
DATE :
AIM:
To write a program for system calls of UNIX operating systems (fork, getpid, exit)
ALGORITHM:
1. Start the program.
2. Declare the variables pid, pid1, pid2.
3. Call fork() system call to create process.
4. If pid==-1, exit.
5. If pid!=-1 , get the process id using getpid().
6. Print the process id.
7. Stop the program
PROGRAM:
#include<stdio.h>
#include<unistd.h>
main()
{
int pid,pid1,pid2;
pid=fork();
if(pid==-1)
{
printf(“ERROR IN PROCESS CREATION \n”);
exit(1);
}
if(pid!=0)
{
pid1=getpid();
printf(“\n the parent process ID is %d\n”, pid1);
}
else
{
pid2=getpid();
printf(“\n the child process ID is %d\n”, pid2);
}}
OUTPUT:
cc fork.c
./a.out
The child process ID is 8640
The parent process ID is 8644
RESULT:
Thus a program for system calls of UNIX operating systems (fork, getpid, exit) waswritten
and executed successfully.
27
EX.NO: 3(C) SIMULATION OF LS UNIX COMMAND
DATE :
AIM:
To write a program for simulation of LS command.
ALGORITHM:
1. Start the program
2. Open the directory with directory object dp
3. Read the directory content and print it.
4. Close the directory.
PROGRAM:
#include<stdio.h>
#include<dirent.h> main(int
argc, char **argv)
{
DIR *dp;
struct dirent *link;
dp=opendir(argv[1]);
printf(“\n contents of the directory %s are \n”, argv[1]);
while((link=readdir(dp))!=0)
printf(“%s”,link->d_name);
closedir(dp);
}
OUTPUT:
cc list.c
./a.out OS
Contents of the directory OS are
Priority.c
Robin.c
copy
RESULT:
Thus a program for simulation of LS command was written and executed successfully.
28
EX.NO: 3(d) SIMULATION OF GREP UNIX COMMAND
DATE :
AIM:
To write a program for simulation of grep command.
ALGORITHM:
1. Start the program
2. Declare the variables fline[max], count=0, occurrences=0 and pointers *fp,
*newline.
3. Open the file in read mode.
4. In while loop check fgets(fline,max,fp)!=NULL
5. Increment count value.
6. Check newline=strchr(fline, „\n‟)
7. Print the count, fline value and increment the occurrence value.
8. Stop the program
PROGRAM:
#include<stdio.h>
#include<string.h>
#define max 1024
void usage()
{
printf(“usage:\t. /a.out filename word \n “);
}
int main(int argc, char *argv[])
{
FILE *fp;
char fline[max];
char *newline;
int count=0;
int occurrences=0;
if(argc!=3)
{
usage();
exit(1);
}
if(!(fp=fopen(argv[1],”r”)))
{
printf(“grep: couldnot open file : %s \n”,argv[1]);
exit(1);
}
while(fgets(fline,max,fp)!=NULL)
{
29
count++;
if(newline=strchr(fline, „\n‟))
*newline=‟\0‟;
if(strstr(fline,argv[2])!=NULL)
{
printf(“%s: %d %s \n”, argv[1],count, fline);
occurrences++;
}
}
}
OUTPUT:
CAT>SAMP
ONE
ONE TWO
THREE FOUR
cc grep.c
./a.out samp one
Samp: 1 one
Samp: 2 one two
RESULT:
Thus a program for simulation of grep command was written and executed
successfully.
30
EX.NO: 4(a) SHELL PROGRAM TO CHECK THE GIVEN NUMBER IS ODD OR EVEN
DATE :
AIM:
To write a shell program to check the given number is odd or even.
ALGORITHM:
1. Start the program.
2. Read the value of n.
3. Calculate “r=expr $n%2‟.
4. If the value of r equals 0 then print the number is even
5. If the value of r not equal to 0 then print the number is odd.
PROGRAM:
OUTPUT:
Enter the number 4
4 is Even number
RESULT:
Thus a shell program to check the given number is odd or even was written and
executed successfully.
31
EX.NO: 4(b) SHELL PROGRAM TO CHECK THE GIVEN YEAR IS LEAP YEAR OR NOT
DATE :
AIM:
To write a shell program to check the given year is leap year or not.
ALGORITHM:
1. Start the program.
2. Read the value of year.
3. Calculate “b=expr $y%4‟.
4. If the value of b equals 0 then print the year is a leap year
5. If the value of r is not equal to 0 then print the year is not a leap year.
PROGRAM:
echo "Enter the year"
read y
b=`expr $y % 4`
if [ $b -eq 0 ]
then
echo "$y is a leap year"
else
echo "$y is not a leap year"
fi
OUTPUT:
Enter the year 2004
2004 is a leap year
RESULT:
Thus a shell program to check the given year is leap year or not was written and
executed successfully.
32
EX.NO: 4(c) SHELL PROGRAM TO FIND THE FACTORIAL OF A NUMBER
DATE :
AIM:
To write a shell program to find the factorial of a number.
ALGORITHM:
1. Start the program.
2. Read the value of n.
3. Calculate “i=expr $n-1‟.
4. If the value of i is greater than 1 then calculate “n=expr $n \* $i‟ and “i=expr $i – 1‟
5. Print the factorial of the given number.
PROGRAM:
OUTPUT:
Enter a number 5
The Factorial of the given Number is 120
RESULT:
Thus a shell program to find the factorial of a number was written and executed
successfully.
33
EX.NO: 4(d) SHELL PROGRAM TO SWAP THE TWO INTEGERS
DATE :
AIM:
To write a shell program to swap the two integers.
ALGORITHM:
1. Start the program.
2. Read the value of a,b.
3. Calculate the swapping of two values by using a temporary variable temp.
4. Print the value of a and b.
PROGRAM:
echo "Enter Two Numbers"
read a b
temp=$a
a=$b
b=$temp
echo "after swapping"
echo $a $b
OUTPUT:
Enter Two Numbers 10 20
After swapping 20 10
RESULT:
Thus a shell program to swap the two integers was written and executed successfully.
34
EX.NO: 5 SIMULATION OF CPU SCHEDULING ALGORITHMS
a) FCFS (First Come First Serve) b) SJF (Shortest Job First)
c) Priority d) Round Robin
DATE :
a) FCFS:
AIM:
A program to simulate the FCFS CPU scheduling algorithm
ALGORITHM :
1. Start the process
2. Get the number of processes to be inserted
3. Get the value for burst time of each process from the user
4. Having allocated the burst time(bt) for individual processes , Start with the first
process from it’s initial position let other process to be in queue
5. Calculate the waiting time(wt) and turn around time(tat) as
Wt(pi) = wt(pi-1) + tat(pi-1) (i.e wt of current process = wt of previous process + tatof
previous process)
6. Calculate the total and average waiting time and turn around time
7. Display the values
8. Stop the process
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
`char pn[10][10];
int arr[10],bur[10],star[10],finish[10],tat[10],wt[10],i,n; int
totwt=0,tottat=0;
clrscr();
printf("Enter the number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Process Name, Arrival Time & Burst Time:");
scanf("%s%d%d",&pn[i],&arr[i],&bur[i]);
}
for(i=0;i<n;i++)
{
if(i==0)
{star[i]=arr[i]; wt[i]=star[i]-arr[i];
35
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
else
{
star[i]=finish[i-1];
wt[i]=star[i]-arr[i];
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
}
printf("\nPName Arrtime Burtime Start TAT Finish");
for(i=0;i<n;i++)
{
printf("\n%s\t%6d\t\t%6d\t%6d\t%6d\t%6d",pn[i],arr[i],bur[i],star[i],tat[i],finish[i]); totwt+=wt[i];
tottat+=tat[i];
}
printf("\nAverage Waiting time:%f",(float)totwt/n);
printf("\nAverage Turn Around Time:%f",(float)tottat/n); getch();
}
OUTPUT:
Enter the number of processes: 3
Enter the Process Name, Arrival Time & Burst Time: 1 2 3
Enter the Process Name, Arrival Time & Burst Time: 2 5 6
Enter the Process Name, Arrival Time & Burst Time: 3 6 7
36
b) SJF:
AIM:
A program to simulate the SJF CPU scheduling algorithm
ALGORITHM
37
strcpy(pn[j],t);
}
}
for(i=0;i<n;i++)
{
if(i==0)
st[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\twaitingtime\ttatime"); for(i=0;i<n;i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],wt[i],ta[i]); printf("\nAverage
waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
getch();
}
OUTPUT:
Enter the number of processes: 3
Enter the Process Name, Arrival Time & Burst Time: 1 4 6
Enter the Process Name, Arrival Time & Burst Time: 2 5 15
Enter the Process Name, Arrival Time & Burst Time: 3 6 11
38
c) Priority:
AIM:
A program to simulate the priority CPU scheduling algorithm
ALGORITHM
39
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];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
else
{
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttatime"); for(i=0;i<n;i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],p[i],wt[i],ta[i]); printf("\nAverage
waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
getch();
}
40
OUTPUT:
Enter the number of processes: 3
Enter the Process Name, Arrival Time, execution time & priority: 1 2 3 1
Enter the Process Name, Arrival Time, execution time & priority: 2 4 5 2
Enter the Process Name, Arrival Time, execution time & priority: 3 5 6 3
1 2 3 1 0 3
2 4 5 2 1 6
3 5 3 5 1 1
Average Waiting Time: 2.0000
Average Turn Around Time: 6.6667
41
d) Round Robin:
AIM:
A program to simulate the Round Robin CPU scheduling algorithm
ALGORITHM:
6. Make the CPU scheduler pick the first process and set time to interrupt after quantum. And
after it's expiry dispatch the process
7. If the process has burst time less than the time quantum then the process is released by the
CPU
8. If the process has burst time greater than time quantum then it is interrupted by the OS
and the process is put to the tail of ready queue and the schedule selects next process
from head of the queue
9. Calculate the total and average waiting time and turnaround time
10. Display the results
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int et[30],ts,n,i,x=0,tot=0;
char pn[10][10];
clrscr();
printf("Enter the no of processes:"); scanf("%d",&n);
printf("Enter the time quantum:"); scanf("%d",&ts);
for(i=0;i<n;i++)
{
printf("enter process name & estimated time:");
scanf("%s %d",pn[i],&et[i]);
}
printf("The processes are:");
for(i=0;i<n;i++)
printf("process %d: %s\n",i+1,pn[i]); for(i=0;i<n;i++)
tot=tot+et[i];
while(x!=tot)
{
42
for(i=0;i<n;i++)
{
if(et[i]>ts)
{
x=x+ts;
printf("\n %s -> %d",pn[i],ts);
et[i]=et[i]-ts;
}
else
if((et[i]<=ts)&&et[i]!=0)
{
x=x+et[i];
printf("\n %s -> %d",pn[i],et[i]);
et[i]=0;}
}}
printf("\n Total Estimated Time:%d",x);
getch();
}
OUTPUT:
Enter the no of processes: 2
Enter the time quantum: 3
Enter the process name & estimated time: p1 12
Enter the process name & estimated time: p2 15
Output:
p1 -> 3
p2 -> 3
p1 -> 3
p2 -> 3
p1 -> 3
p2 -> 3
p1 -> 3
p2 -> 3
p2 -> 3
Total Estimated Time: 27
Result :
Thus the following CPU scheduling program was written and the output was verified successfully.
43
EX NO: 6 IMPLEMENTING SEMAPHORE FOR PRODUCER CONSUMER PROBLEM
DATE :
AIM:
To write a c-program to implement the producer – consumer problem using semaphores.
ALGORITHM:
1. Start the program.
2. Declare the required variables.
3. Initialize the buffer size and get maximum item you want to produce.
4. Get the option, which you want to do either producer, consumer or exit from the operation.
5. If you select the producer, check the buffer size if it is full the producer should not produce
the item or otherwise produce the item and increase the value buffer size.
6. If you select the consumer, check the buffer size if it is empty the consumer should not
consume the item or otherwise consume the item and decrease the value of buffer size.
7. If you select exit come out of the program.
8. Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
int mutex=1,full=0,empty=3,x=0;main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n");while(1)
{
printf("\nENTER YOUR
CHOICE\n"); scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer();
44
else
printf("BUFFER IS FULL");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else
printf("BUFFER IS EMPTY");
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s)
{
return(--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nproducer produces the item%d",x);
mutex=signal(mutex);
45
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\n consumer consumes item%d",x);x--;
}
OUTPUT:-
1. PRODUCER
2. CONSUMER
3. EXIT
ENTER YOUR
:C1HOICE
producer produces the
item2
RESULT:
DATE :
AIM
To developing Application using Inter Process communication (using shared memory, pipes or
message queues)
ALGORITHM
1 . St art t h e p rogr a m.
2. Read the input from parent process and perform in child process.
3. Write the date in parent process and read it in child process.
4. Fibonacci Series was performed in child process. 5 .
Stoptheprogram.
48
if(p->a[i]=='a'||p->a[i]=='e'||p->a[i]=='i'||p->a[i]=='o'||p->a[i]=='u')
{
count=count+1;
}
}
printf("The number of vowels in the string is %d \n",count);
}
else
flag1=1;
}
if((flag==1)&&(flag1==1))
break; }
msgctl(id,IPC_RMID,NULL);
}
Client1:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
struct msgbuf
{
long mtype;
char a[100];
};
struct msgbuf *p;
int main()
{
int id;
id=msgget((key_t)4066,0733);
p=(struct msgbuf *)malloc(sizeof(struct msgbuf)); do
{
49
printf("Enter the string:\n");
printf("Type quit for exit:\n");
scanf("%s",p->a);
p->mtype=1;
msgsnd(id,p,601,0);
}
while(strcmp(p->a,"quit")!=0);
}
Client2:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h> struct
msgbuf
{
long mtype;
char a[100];
};
struct msgbuf *p;
int main()
{
int id;
id=msgget((key_t)4066,0733);
p=(struct msgbuf *)malloc(sizeof(struct msgbuf)); do
{
printf("Enter the string \n");
printf("Type quit 4r exit \n");
scanf("%s",p->a);
p- >mtype=2; msgsnd(id,p,601,0);
}
while(strcmp(p->a,"quit")!=0);
50
}
OUTPUT:
Server: waiting for client queries……..
Client1:enter the string
Type quit for exit
Madam
Server: the string is palindrome
Client2: enter the string
Type quit for exit
Computer
Server:
The no.of vowels in the string is 3
RESULT
51
Ex.No : 8 . BANKERS ALGORITHM FOR DEADLOCK AVOIDANCE
DATE :
.
AIM:
A program to simulate the Bankers Algorithm for Deadlock Avoidance
.ALGORITHM:
1. Start the program.
7. If the new request comes then check that the system is in safety. Or
not if we allow the request.
PROGRAM:
#include<stdio.h>
int main() {
printf("%d\t", need[i][j]);
printf("\n");
/* once process execute variable done will stop them for again execution */
done[i] = 0;
if (done[i] == 0) {
53
for (j = 0; j < c; j++) {
break;
//when need matrix is not greater then available matrix then if j==c will true
if (j == c) {
safe[count] = i;
done[i] = 1;
/* now process get execute release the resources and add them in available resources */
available[j] += alc[i][j];
count++;
terminate = 0;
} else {
terminate++;
if (terminate == (p - 1)) {
break;
if (terminate != (p - 1)) {
54
printf("%d\t", available[i]);
printf("p%d\t", safe[i]);
} }
return 0;
OUTPUT :
5 3
010
200
302
211
002
753
322
902
422
533
7 4 3
1 2 2
6 0 0
55
2 1 1
5 3 1
10 5 7
p1 p3 p4 p0 p2
RESULT:
Thus a program to simulate Bankers Algorithm for Deadlock Avoidance was written and
output was verified successfully.
56
EX.NO:9 BANKERS ALGORITHM FOR DEADLOCK PREVENTION.
DATE :
AIM:
A program to simulate Bankers Algorithm for Deadlock Prevention.
ALGORITHM:
1. Start the program
2. Attacking Mutex condition: never grant exclusive access. But this may not be possible for
several resources.
3. Attacking preemption: not something you want to do.
4. Attacking hold and wait condition: make a process hold at the most 1 resource
5. At a time. Make all the requests at the beginning. Nothing policy. If you feel, retry.
6. Attacking circular wait: Order all the resources. Make sure that the requests are issued in the
7. Correct order so that there are no cycles present in the resource graph. Resources
numbered 1 ... n.
8. Resources can be requested only in increasing
9. Order. i.e. you cannot request a resource whose no is less than any you may be holding.
10. Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int cl[10][10],al[10][10],av[10],i,j,k,m,n,ne[10][10],flag=0; clrscr();
printf("\nEnter the matrix");
scanf("%d %d",&m,&n);
printf("\nEnter the claim matrix:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cl[i][j]);
}
}
57
printf("\nEnter allocated matrix:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&al[i][j]);
}
}
printf("\nThe need matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
ne[i][j]=cl[i][j]-al[i][j];
printf("\t%d",ne[i][j]);
}
printf("\n");
}
printf("\nEnter avaliable matrix");
for(i=0;i<n;i++)
scanf("%d",&av[i]);
printf("Claim matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",cl[i][j]);
}
printf("\n");
}
printf("\n Allocated matrix:\n");
for(i=0;i<m;i++)
{
58
for(j=0;j<n;j++)
{
printf("\t%d",al[i][j]);
}
printf("\n");
}
printf("Available matrix:\n");
for(i=0;i<n;i++)
{
printf("%d\t",av[i]);
}
//for(k=0;k<m;k++)
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(av[j]>=ne[i][j])
flag=1;
else
flag=0;
}
}
if(flag==0)
printf("Unsafe State");
else
printf("Safe State");
getch();
}
59
OUTPUT:
Input:
Enter the claim matrix:3 2 2 6 1 3 3 1 4 4 2 2
Enter allocated matrix:1 0 0 5 1 1 2 1 1 0 0 2
The need matrix:
222
102
103
420
Enter available matrix1 1 2
Output:
Claim matrix:
322
613
314
422
Allocated matrix:
100
511
211
002
Available matrix:
1 1 2 Safe State
RESULT
Thus a program to simulate Bankers Algorithm for Deadlock Prevention was written and
output was verified successfully.
60
E X.NO :10 Implementation of Threading concept
DATE :
AIM :
To write and execute C programs that demonstrate various thread-related concepts using the POSIX
thread (pthreads) library, including thread creation, joining and passing data to threads.
ALGORITHM:
Step 1 :Define a thread function (printNumber) that prints the thread index.
1. Assign an index.
2. Create the thread and pass the index.
PROGRAM :
#include <stdio.h>
#include <pthread.h>
void* threadFunction(void* arg) {
int id = *(int*)arg;
printf("Thread %d is running.\n", id);
return NULL;
}
int main() {
pthread_t threads[5];
int ids[5];
ALGORITHM:
1. Declare structures hole and process to hold information about set of holes and
processes respectively.
Get number of holes, say nh.
Get the size of each hole
Get number of processes, say np.
Get the memory requirements for each process.
Allocate processes to holes, by examining each hole as follows:
If hole size > process size then
Mark process as allocated to that hole.
Decrement hole size by process size.
Otherwise check the next from the set of hole
Print the list of process and their allocated holes or unallocated status.
Print the list of holes, their actual and current availability.
Stop
PROGRAM:
#include <stdio.h>
structprocess
main()
62
}
printf("\nEnternumber of process:"); scanf("%d",&np);
for(i=0;i<np;i++)
{
printf("enter the size of process P%d :",i); scanf("%d", &p[i].size); p[i].flag
= 0;
}
for(i=0; i<np; i++)
{
for(j=0; j<nh; j++)
{
if(p[i].flag != 1)
{
if(p[i].size <=h[j].size)
{
p[i].flag = 1; p[i].holeid = j; h[j].size -=
p[i].size;
}
}
}
}
OUTPUT:
$ gcc ffit.c
$ ./a.out
Enter the number of Holes :5
Enter size for hole H0 : 100
Enter size for hole H1 : 500
Enter size for hole H2 : 200
Enter size for hole H3 : 300
Enter size for hole H4 :600
ALGORITHM:
2. Find the block with the smallest size that is big enough to fit the process (i.e., minimal wastage).
o Mark the block as occupied (or reduce its available size accordingly).
PROGRAM:
#include <stdio.h>
int main() {
int blockSize[20], processSize[20], blockCount, processCount;
int allocation[20];
64
printf("Enter the size of each memory block:\n");
for (int i = 0; i < blockCount; i++) {
printf("Block %d: ", i + 1);
scanf("%d", &blockSize[i]);
}
return 0;
}
AIM :
To allocate memory requirements for processes using w o r s t fit allocation.
ALGORITHM:
65
1. Start the program.
o Update fragmentation:
bf[ff[i]] = 1.
File number,
File size,
Block size,
Internal fragmentation.
66
6. End the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - worst Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
OUTPUT:
67
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
RESULT:
Thus a program to simulate memory allocation scheme was written and output was verified
successfully.
68
EX.NO: 12 IMPLEMENT PAGING TECHNIQUE OF MEMORY MANAGEMENT
Date :
AIM:
A program to simulate Paging technique of memory management.
ALGORITHM:
Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks. Step
3: Frames – Physical memory is broken into fixed – sized blocks. Step 4:
Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
Step 5: Display the physical address.
Step 6: Stop the process.
PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int np,ps,i;
int *sa;
clrscr();
printf("Enter how many pages\n");
scanf("%d",&np);
printf("Enter the page size \n");
scanf("%d",&ps); for(i=0;i<np;i++)
{
sa[i]=(int)malloc(ps);
printf("Page%d\t Address %u\n",i+1,sa[i]);
}
getch();
}
OUTPUT:
Enter how many pages: 5
Enter the page size: 4
Page1 Address: 1894
Page2 Address: 1902
Page3 Address: 1910
Page4 Address: 1918
Page5 Address: 1926
RESULT:
Thus the program to simulate Paging technique of memory management was written and the output was
verified successfully.
69
Ex.No:13 SIMULATE PAGE REPLACEMENT ALGORITHMS
Date:
ALGORITHM:
Step 1: create a queue to hold all pages in memory
Step 2: when the page is required replace the page at the head of the queue
Step 3: now the new page is inserted at the tail of the queue
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],b[20],n,p=0,q=0,m=0,h,k,i,q1=1;
char f='F';
clrscr();
printf("Enter the Number of Pages:");
scanf("%d",&n);
printf("Enter %d Page Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
{if(p==0)
{
if(q>=3)
q=0;
a[q]=b[i];
q++;
if(q1<3)
{
q1=q;
70
}
}
printf("\n%d",b[i]);
printf("\t");
for(h=0;h<q1;h++)
printf("%d",a[h]);
if((p==0)&&(q<=3))
{
printf("-->%c",f);
m++;
}
p=0;
for(k=0;k<q1;k++)
{
if(b[i+1]==a[k])
p=1;
}
}
printf("\nNo of faults:%d",m);
getch();
}
OUTPUT:
Input:
Enter the Number of Pages: 12
Enter 12 Page Numbers:
232152453252
Output:
2 2-> F
3 23-> F
2 23
1 231-> F
5 531-> F
2 521-> F
4 524-> F
5 524
71
3 324-> F
2 324
5 354-> F
2 352-> F
No of faults: 9
AIM:
A program to simulate LRU Page Replacement Algorithm
ALGORITHM:
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the queue
Step 3: Now the new page is inserted at the tail of the queue
Step 5: When the page fault occurs replace page present at the bottom of the stack
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int
g=0,a[5],b[20],p=0,q=0,m=0,h,k,i,q1=1,j,u,n;
char f='F';
clrscr();
printf("Enter the number of pages:");
scanf("%d",&n);
printf("Enter %d Page Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
{if(p==0)
{
72
if(q>=
3)
q=0;
a[q]=b[
i]; q++;
if(q1<3)
{
q1=q;
}}
printf("\n%d",b[i]);
printf("\t");
for(h=0;h<q1;h++)
printf("%d",a[h]);
if((p==0)&&(q<=3))
{
printf("-->%c",f);
m++;
}
p=
0;
g=
0;
if(q1==3)
{
for(k=0;k<q1;k++)
{
if(b[i+1]==a[k]) p=1;
}
for(j=0;j<q1;j++)
{
u=
0;
k=i;
while(k>=(i-1)&&(k>=0))
{
73
if(b[k]==a[j])
u++; k--;}
if(u==0)
q=j;
}}
else {
for(k=0;k<q;k++)
{
if(b[i+1]==a[k
]) p=1;
} }}
printf("\nNo of faults:%d",m);
getch();}
OUTPUT:
Enter the Number of Pages:
12
74
EX.NO :14 IMPLEMENTATION OF THE VARIOUS FILE ORGANIZATION TECHNIQUES
DA T E:
AIM:
Write a C program to simulate the following file organization techniques. Such as
a) Single level directory b) Two level directory c) Hierarchical
ALGORITHM :
1. Start the program.
2. Define a structure directory containing:
o fname (file name),
o dname (directory name).
3. Initialize:
o Array dir[] of structure type to store files and directory,
o Variables count, ch, f[], d[].
4. Display a menu repeatedly (inside a while(1) infinite loop):
5. Take user's choice (ch) as input.
6. Perform operations based on user's choice:
o Case 1: Create Directory
If no directory exists (count == 0), ask for directory name and create it.
Else, display that directory already exists.
o Case 2: Create File
If directory doesn't exist, prompt to create directory first.
Else, ask for file name and add it under the directory.
Increment count.
o Case 3: Delete File
If no files exist, display message.
Else, ask for file name to delete.
Search through existing files.
If found, remove (empty the name).
Else, show "file not found."
o Case 4: Search File
If no files exist, show message.
Else, search for given file name.
If found, display message.
Else, show "file not found."
o Case 5: Display Directory
If no directory exists, show message.
Else, print directory name and list all files created.
o Case 6: Exit
Exit the program.
75
7. Repeat the process until user selects Exit.
PROGRAM:
#include <stdio.h>
#include <string.h>
struct directory
{
char fname[10];
char dname[10];
} dir[10];
void main()
{
int i, ch, count = 0;
char f[10];
char d[10];
while (1)
{
printf("\n1. Create Directory\n2. Create File\n3. Delete File\n4. Search File\n5. Display Directory\n6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
if (count == 0) {
printf("Enter name of directory: ");
scanf("%s", dir[count].dname);
printf("Directory created.\n");
} else {
printf("Directory already exists!\n");
}
break;
case 2:
if (count == 0) {
printf("No directory found. Create a directory first.\n");
} else {
printf("Enter file name: ");
scanf("%s", dir[count].fname);
printf("File created.\n");
count++;
}
76
break;
case 3:
if (count == 0) {
printf("No files to delete.\n");
} else {
printf("Enter file name to delete: ");
scanf("%s", f);
for (i = 1; i < count; i++) {
if (strcmp(f, dir[i].fname) == 0) {
printf("File %s deleted.\n", f);
strcpy(dir[i].fname, ""); // delete file
break;
}
}
if (i == count)
printf("File not found.\n");
}
break;
case 4:
if (count == 0) {
printf("No files to search.\n");
} else {
printf("Enter file name to search: ");
scanf("%s", f);
for (i = 1; i < count; i++) {
if (strcmp(f, dir[i].fname) == 0) {
printf("File %s found.\n", f);
break;
}
}
if (i == count)
printf("File not found.\n");
}
break;
case 5:
if (count == 0) {
printf("No directory and files to display.\n");
} else {
printf("\nDirectory name: %s\n", dir[0].dname);
printf("Files:\n");
for (i = 1; i < count; i++) {
if (strcmp(dir[i].fname, "") != 0)
printf("%s\n", dir[i].fname);
77
}
}
break;
case 6:
printf("Exiting...\n");
return;
default:
printf("Invalid choice!\n");
}
}
}
OUTPUT:
Single Level Directory Implementation
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 1
Enter name of directory: mydir
Directory created.
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 2
Enter file name: file1
File created.
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 2
78
Enter file name: file2
File created.
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 5
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 4
Enter file name to search: file1
File file1 found.
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 3
Enter file name to delete: file2
File file2 deleted.
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
79
6. Exit
Enter your choice: 5
1. Create Directory
2. Create File
3. Delete File
4. Search File
5. Display Directory
6. Exit
Enter your choice: 6
Exiting...
ALGORITHM:
Step1: Create Root Directory:
o Use the mkdir("root", 0755) function to create a root directory named root.
o Check if the directory creation is successful. If it fails, print an error and terminate the program.
Step 2:Create Subdirectories Inside Root:
o Use the mkdir("root/subdir1", 0755) function to create a subdirectory named subdir1 inside the
root directory.
o Use the mkdir("root/subdir2", 0755) function to create another subdirectory named subdir2
inside the root directory.
o Check if each directory creation is successful. If either fails, print an error and terminate the
program.
Step3:Create Files Inside Subdirectories:
o Open file1.txt inside subdir1 using fopen("root/subdir1/file1.txt", "w"). Write some content to
the file and close it.
o Open file2.txt inside subdir2 using fopen("root/subdir2/file2.txt", "w"). Write some content to
the file and close it.
o If file creation or writing fails, print an error and terminate the program.
Step4:List Contents of Root Directory:
o Use opendir("root") to open the root directory.
o Use readdir() in a loop to read and print the entries inside the root directory (including subdir1,
subdir2, and the . and .. entries).
o Close the root directory using closedir().
Step5:List Contents of Subdirectory 1:
o Use opendir("root/subdir1") to open the subdir1 directory.
o Use readdir() in a loop to read and print the entries inside subdir1 (including file1.txt and the .
and .. entries).
o Close subdir1 using closedir().
Step6:List Contents of Subdirectory 2:
o Use opendir("root/subdir2") to open the subdir2 directory.
o Use readdir() in a loop to read and print the entries inside subdir2 (including file2.txt and the .
80
and .. entries).
o Close subdir2 using closedir().
Step7: End Program:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void createDirectories() {
// Create a root directory
if (mkdir("root", 0755) == -1) {
perror("Error creating root directory");
exit(1);
}
void listDirectories() {
DIR *d;
struct dirent *dir;
// List subdir2
snprintf(subdirPath, sizeof(subdirPath), "root/subdir2");
d = opendir(subdirPath);
if (d) {
printf("\nContents of subdir2:\n");
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
} else {
perror("Error opening subdir2");
}
}
int main() {
// Create the two-level directory structure
createDirectories();
return 0;
}
OUTPUT:
Directories and files created successfully.
Contents of root:
.
..
subdir1
subdir2
Contents of root/subdir1:
.
82
..
file1.txt
Contents of root/subdir2:
.
..
file2.txt
ALGORITHM:
Step 1: Define Structures
Define a structure File to store file names.
Define a structure Directory to store:
o Directory name,
o Array of files,
o Array of subdirectories,
o File count and subdirectory count.
Step 2: Create Root Directory
Allocate memory dynamically (malloc) for the root directory.
Initialize:
o Name of root ("root"),
o Set file count = 0,
o Set subdirectory count = 0.
Step 3: Create Subdirectories and Files
Create Directory Function:
o Take a parent directory and a directory name.
o Allocate memory for a new directory.
o Copy the name into the new directory.
o Set its file count and subdirectory count to 0.
o Attach this new directory to the parent's subdirectory list.
Create File Function:
o Take a directory and file name.
o Add the file to the directory’s file list.
o Increase the file count by 1.
Step 4: Build Hierarchy
Using createDirectory() and createFile() functions:
o Create subdirectories and files under the root and further under subdirectories.
o Example:
Create subdir1 inside root.
Create subsubdir1 inside subdir1.
Create files at different levels.
Step 5: Display the Directory Structure
o Print the current directory’s name.
o For each file inside the directory:
Print the file name with appropriate indentation.
o For each subdirectory inside the directory:
Recursively call the display function, increasing the indentation.
Step 6: End Program
83
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct File {
char name[50];
};
struct Directory {
char name[50];
struct File files[10];
int fileCount;
struct Directory *subDirs[10];
int subDirCount;
};
int main() {
struct Directory *root = (struct Directory *)malloc(sizeof(struct Directory));
strcpy(root->name, "root");
root->fileCount = 0;
84
root->subDirCount = 0;
// Creating structure
createDirectory(root, "subdir1");
createFile(root, "file1.txt");
createDirectory(root->subDirs[0], "subsubdir1");
createFile(root->subDirs[0], "file2.txt");
createFile(root->subDirs[0]->subDirs[0], "file3.txt");
createDirectory(root, "subdir2");
createFile(root->subDirs[1], "file4.txt");
return 0;
}
OUTPUT:
RESULT:
Thus the C program to simulate the file organization techniques was written and output was
verified successfully.
85
Ex.No 15A IMPLEMENTATION OF FILE ALLOCATION STRATEGIES
AIM :
To implement Sequential file allocation in C.
ALGORITHM:
Step 1: Initialize Memory
Create an array memory[50], initialized to 0.
o (0 → free block, 1 → occupied block)
Step 2: Input Number of Files
Ask the user to enter the number of files n.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct File {
char name[20];
int startBlock;
int length;
};
int main() {
int memory[50] = {0}; // 0 means free, 1 means occupied
86
struct File files[10];
int n, i, j, totalFiles = 0;
if (flag == 0) {
// Allocate the file
for (j = files[totalFiles].startBlock; j < (files[totalFiles].startBlock + files[totalFiles].length); j++) {
memory[j] = 1;
}
totalFiles++;
printf("File allocated successfully.\n");
} else {
printf("Error: Blocks already allocated, can't allocate file '%s'.\n", files[totalFiles].name);
}
}
return 0;
}
87
OUTPUT:
RESULT:
Thus the C program to implement sequential file allocation was written and output was
verified successfully.
88
EX.NO:15b INDEXED FILE ALLOCATION
DATE:
AIM:
To implement Indexed file allocation technique in C.
ALGORITHM:
1. Start
2. Declare the index block no. and total no.of files in a block
3. Get the index block no. and total no.of files in a block from the user.
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
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct File {
char name[20];
int indexBlock;
int blocks[10];
int length;
};
int main() {
int memory[50] = {0}; // 0 = free, 1 = allocated
struct File files[10];
int n, i, j, totalFiles = 0;
89
printf("Enter number of blocks needed: ");
scanf("%d", &files[totalFiles].length);
if (!indexBlockFound) {
printf("Error: No free block available for index block!\n");
continue;
}
if (memory[blockNum] == 0) {
files[totalFiles].blocks[j] = blockNum;
memory[blockNum] = 1;
} else {
printf("Block %d is already allocated! Cannot assign.\n", blockNum);
success = 0;
break;
}
}
if (success) {
totalFiles++;
printf("File allocated successfully.\n");
} else {
// Rollback allocation if failure
memory[files[totalFiles].indexBlock] = 0;
for (int k = 0; k < j; k++) {
memory[files[totalFiles].blocks[k]] = 0;
90
}
printf("File allocation failed. Try again.\n");
}
}
return 0;
}
OUTPUT:
Enter the number of files: 2
RESULT:
Thus the C program to implement indexed file allocation was written and output was
verified successfully.
91
EX.NO. 16 Disk Scheduling Algorithms
DATE :
AIM:
A) FCFS :
ALGORITHM:
Step 3: Process Each Request for each request in the order they were entered:
Step 4: Print the order of service (head movement path) and total head movement
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, initial, totalMovement = 0;
int request[100];
printf("Enter the number of disk requests: ")
scanf("%d", &n);
printf("Enter the disk request sequence:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &request[i]);
}
92
printf("Enter the initial head position: ");
scanf("%d", &initial);
printf("\nOrder of service:\n");
printf("%d", initial);
for (i = 0; i < n; i++)
{
totalMovement += abs(request[i] - initial);
initial = request[i];
printf(" -> %d", initial);
}
printf("\n\nTotal head movement = %d cylinders\n", totalMovement);
return 0;
}
OUTPUT :
Order of service:
53 -> 98 -> 183 -> 37 -> 122 -> 14
B) SCAN
ALGORITHM:
Step 1: Start the program
Read the number of disk requests n.
Read the disk request sequence into array request[].
Read the initial head position (head).
Read the total disk size (disk_size).
Step 2: Add Special Points
Insert the initial head position into the request list.
Insert 0 into the request list (assuming the head moves toward 0
first).
Step 3: Sort the request[] array in ascending order (using bubble sort or any sorting
technique).
Step 4: Find the index (position) of the head in the sorted request array.
Step 5: Service Requests
1. Move left (toward 0):
o From the head's position, move backward in the sorted
array.
o For each movement:
Print the current request.
Add the absolute difference between current and
next request to total movement.
93
2. Move right (after reaching 0):
o After reaching the start (0), move forward in the sorted
array.
o For each movement:
Print the current request.
Add the absolute difference between current and
next request to total movement.
Step 6: Display the order of head movements and total head movement.
PROGRAM:
#include <stdlib.h>
int main() {
int n, head, disk_size, i, j;
int request[100];
94
sort(request, n);
int total_movement = 0;
printf("\nOrder of service:\n");
return 0;
}
OUTPUT:
Enter the number of disk requests: 5
Enter the disk request sequence:
82 170 43 140 24
Enter the initial head position: 50
Enter the total disk size (max cylinder number): 200
Order of service:
50 43 24 82 140 170 0
95
C) C-SCAN
ALGORITHM:
1. Define Event Structure: Create a structure to store event details such as the event
name and priority.
2. Initialize Event Array: Store predefined events in an array, each having a name and
a priority value.
3. Display Events: Create a function to display all the events and their priorities.
5. Remove Scheduled Event: After scheduling, remove the event from the array by
shifting the remaining events.
6. Repeat the Process: Continue scheduling the next event until no events are left in the
array.
PROGRAM:
#include <stdio.h>
#include <string.h>
// Find the event with the highest priority (smallest priority value) int
min_priority_index = 0;
96
for (int i = 1; i < n; i++) {
if (events[i].priority < events[min_priority_index].priority) {
min_priority_index = i;
}
}
// Number of events
int n = 3;
97
scheduleNextEvent(events, n);
n--; // Decrease number of events after
scheduling displayEvents(events, n);
}
return 0;
}
OUTPUT:
Current events in the queue:
Event: Meeting with
team, Priority: 2 Event:
Submit report, Priority: 1
Event: Client call,
Priority: 3
RESULT:
98
EX.NO . Selfish Round Robin CPU scheduling
DATE :
AIM:
write a c program for Selfish Round Robin CPU Scheduling
ALGORITHM:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
int burst_time;
int remaining_time;
int priority;
int completed;
99
} Process;
int main() {
int n, time_quantum;
printf("Enter the number of processes: ");
scanf("%d", &n);
Process p[n];
printf("Enter burst time and priority (lower number = higher priority) for each
process:\n");
for (int i = 0; i < n; i++) {
p[i].id = i + 1;
printf("Process %d Burst Time: ", i + 1);
scanf("%d", &p[i].burst_time);
printf("Process %d Priority: ", i + 1);
scanf("%d", &p[i].priority);
p[i].remaining_time = p[i].burst_time;
p[i].completed = 0;
}
printf("Enter the time quantum: ");
scanf("%d", &time_quantum);
int total_time = 0;
int completed_processes = 0;
printf("\nExecution Order:\n");
while (completed_processes < n) {
int min_priority = 9999;
int index = -1;
// Find process with highest priority (smallest priority number)
for (int i = 0; i < n; i++) {
if (p[i].completed == 0 && p[i].priority < min_priority) {
min_priority = p[i].priority;
index = i;
}
}
if (index == -1) {
break; // No more processes left
}
// Execute selected process
printf("P%d ", p[index].id);
100
printf("\nTotal execution time: %d units\n", total_time);
return 0;
}
OUTPUT:
Enter the number of processes: 4
Enter burst time and priority (lower number = higher priority) for each process:
Process 1 Burst Time: 10
Process 1 Priority: 2
Process 2 Burst Time: 5
Process 2 Priority: 1
Process 3 Burst Time: 8
Process 3 Priority: 3
Process 4 Burst Time: 6
Process 4 Priority: 2
Enter the time quantum: 4
Execution Order:
P2 P1 P4 P1 P4 P1 P3 P3
Total execution time: 29 units
RESULT:
Thus the C program to implement selfish round robin scheduling algorithm was written and
output was verified successfully.
101