0% found this document useful (0 votes)
2 views45 pages

OS Lab Manual Modified

The document is a lab manual for operating system experiments focusing on UNIX commands, system calls, and CPU scheduling algorithms. It includes detailed explanations and examples of various UNIX commands, programming exercises to simulate these commands, and implementations of CPU scheduling algorithms like Round Robin, SJF, and FCFS. Each experiment provides source code and expected outputs for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views45 pages

OS Lab Manual Modified

The document is a lab manual for operating system experiments focusing on UNIX commands, system calls, and CPU scheduling algorithms. It includes detailed explanations and examples of various UNIX commands, programming exercises to simulate these commands, and implementations of CPU scheduling algorithms like Round Robin, SJF, and FCFS. Each experiment provides source code and expected outputs for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

OperatingSystemLabManual

ExperimentNo-1:

Aim: PracticingofBasicUNIXCommands.

1 a.)Study of Unix/Linux general purpose utility command list: man,who,cat, cd,

cp,ps,ls,mv,rm,mkdir,rmdir,echo,more,date,time,kill,history,chmod,chown, finger,

pwd, cal, logout, shutdown.

1. cal: This command is used to show the calendar.


Syntax: cal [[month] year]
Examples: If we need to show the calendar for March 2018, we can use the following Unix command:
$ cal 3 2018
2. date: It is used to show the system time and date.
Syntax: date [+format]
Examples: If we need to show the date in dd/mm/yy format, we can use the following Unix command:
$ date +%d/%m/%y
3. df: This command displays the total free blocks for a mounted file system.
Syntax: $ df [options] [file]
Example,
$ df -l
The above command will show the total free blocks inside the local file systems.
4. who: This command is used to show the user's list logged in currently.
Syntax: who [option] ... [file][arg1]
Example: We can use the following command to list every user logged in currently:
$ who
5. whoami: This command is used to show the user id logged in currently.
Syntax: whoami [option]
Example: We can use the following command to list the users logged in currently:
$ whoami
6. touch: It creates a new file or upgrades its timestamp.
Syntax: touch [OPTION]...[FILE]
Example: We can use the following command to make empty files:
$ touch file1 file2
7. cat: This command is used to concatenate files and display them on stdout.
Syntax: cat [OPTION]...[FILE]
Example: We can use the following command to make a file along with entered content:
$ cat> file1
Hello
^D
8. copy: This command is used to copy files.
Syntax: cp [OPTION] source destination
Examples: We can use the following command to copy the contents of text1 and text2, and the contents of
text1 are retained:
$ cp text1 text2
9. mv: This command is used to rename files or move files.
Syntax: mv [OPTION] source destination
Examples: We can use the following command to make empty files known as text1 and text2:
$ mv text1 text2

10.rm: This command is used to remove directories and files.


Syntax: rm [OPTION]...[FILE]
Example: We can use the following command to delete text1:
$ rm file1
11. mkdir:It creates a directory.
Syntax: mkdir [OPTION] directory
Example: We can use the following command to make a directory:
$ mkdir direct1
12. rmdir:It removes a directory.
Syntax: rmdir [OPTION] directory
Example: We can use the following command to make empty files:
$ rmdir direct1
13.cd:It changes the directory.
Syntax: cd [OPTION] directory
Example: We can use the following command to change our working directory:
$ cd direct1
14.pwd:It prints the current working directory.
Syntax: pwd [OPTION]
Example: We can use the following command to print "direct1" if our current working directory is "direct1":
$ pwd
15.ps:It shows a snapshot of every current process.
Syntax: $ ps [options]
Example,
$ ps -ef
The above command will display all running processes formatted as a table.
16. top: It shows a live current process status.
Syntax: $ top [options]
Example,
$ top
The above command will display a live view of every current process.
17.bg: It remains a background suspended a job.
Syntax: $ bg [job_spec...]
Example: $ xterm
Ctrl-Z
$ bg
The above command will continue executing a job that was suspended in the background previously.
18. fg: It brings a job to the foreground from the background.
Syntax: $ fg [job_spec...]
Example,
$ xterm
Ctrl-Z
$ bg
$ fg
The above command will bring a previous job to the foreground from the background.
19. clear: It clears the terminal screen.
Syntax: $ clear
Example,
$ clear
The above command will clear every prior text through the terminal window.
20. history: It prints the command history in the current active session.
Syntax: $ top [options]
Example,
$ clear
The above command will display the list of old commands that were enrolled.
21. ls: It lists the contents of the directories.
Syntax: $ ls [options] [FILE]
Example,
$ ls -alt
The above command will list every content of a directory in a long way sorted by time.
22. which: It locates the commands.
Syntax: $ which [-a] filename
Example,
$ which [-a] cat
The above command will list every path from where 'cat' can execute.
23. man:It is an interface to work with online reference manuals.
Syntax: $ man [-s section] item
Example,
$ man cat
The above command will display the manual page for 'cat'.
24. su: It modifies user-id and becomes a super or root user.
Syntax: $ su [options] [username]
Example,
$ su user1
The above command will modify the specified user-id.
25. sudo: It runs the command as other super-users or users.
Syntax: $ sudo [options] [command]
Example,
$ sudols /usr/local/protected
The above command will get the file listing of the unlisted directory.
26. find: This command is used to find directories and files.
Syntax: $ find [starting-point] [expression]
Example,
$ find /usr -type c -name text
The above command will search for character device files of the 'text' name in the '/usr' folder.

27. du: It estimates the disk usage blockage.


Syntax: $ du [options] [file]
Example,
$ du
The above command will display the total blocks utilized by files within the current directory.

28. df: This command displays the total free blocks for a mounted file system.
Syntax: $ df [options] [file]
Example,
$ df -l
The above command will show the total free blocks inside the local file systems.

ExperimentNo-2:

Aim:WriteprogramsusingthefollowingUNIX operatingsystemcalls

A. open,read,write,seekandclo

se Source code :

2. #include<stdio.h>
3. #include<conio.h>//
4. getch()
5. int main()
6. {
7. FILE *file;
8. char buffer[100];
9. file=fopen("testfile.txt","w+");//"w+"
10. if (file == NULL)
11. {
12. printf("Erroropening/creatingfile.\n
"); return 1;
13. }
14. fprintf(file,"Hello,Students");
fseek(file, 0, SEEK_SET);
15. fgets(buffer,100,file);
16. printf("Content read from file:%s\n", buffer);

17. fclose(file);
18. getch();//Waitforkeypressbeforeexiting(specifictoTurboC++
) return 0;
19. }
20.
21.
22.
23. Output:
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
opendir,closedir Source code :
37. #include<stdio.h>
38. #include<stdlib.h>
39. #include<dirent.h>
40. #include<conio.h>
41. int main (void)
42. {
43. DIR *d;

44. Struct dir ent *dir;


45. char*directory_path="";//"."referstothecurrentdirectory
clrscr();
46. printf("\n Enter path of the directory...!\n");
printf("\Forexample:'C:/TURBOC3/SOURCE':\n");
scanf("%s",directory_path);
47. d=opendir(directory_path);
48. if (d)
49. {
50. while((dir=readdir(d))!=NULL)
51. {
52. printf("%s\n", dir->d_name);
53. }
54. closedir(d);
55. }
56. else
57. {
58. perror("Unabletoopendirectory");
59. return EXIT_FAILURE;
60. }
61. getch();
62. return EXIT_SUCCESS;
63. }

64.
65. Output: C:/TURBOC3/Sourcedir1 file1.txt
66. file2.c subdir1 program.exe

67. C:/TURBOC3/Sourcedir2
68.
69.
70.

ExperimentNo-3:

AIM:

TowriteCprogramstosimulateUNIXcommandslikecp,ls,grep.

1. Programforsimulation ofcpunixcommands

Sourcecode:
#include <stdio.h>
#include<stdlib.h>

intmain(intargc,char*argv[]){
FILE *source, *destination;
char ch;

if(argc!=3){
printf("Usage:./cp_simulation<source_file><destination_file>\n");
return 1;
}
source=fopen(argv[1],"r"); if
(source == NULL) {
printf("Unabletoopensourcefile:%s\n",argv[1]);
return 1;
}

destination=fopen(argv[2],"w"); if
(destination == NULL) {
printf("Unabletoopenor createdestinationfile:%s\n", argv[2]);
fclose(source);
return1;
}

while((ch=fgetc(source))!=EOF){
fputc(ch, destination);
}
fclose(source);
fclose(destination);

printf("Filecopiedsuccessfully.\n");

return0;
}

Output:./cp_simulationsource.txtdestination.txt

File copied successfully.

2. Programforsimulationoflsunixcommands

Sourcecode:

#include<stdio.h>

#include<dirent.h>

main(intargc,char**argv)

DIR*dp;

structdirent*link;
dp=opendir(argv[1]);

printf(“\ncontentsofthedirectory%sare\n”,argv[1]);while((link=readdir(dp))!=0)
printf(“%s”,link->d_name);
closedir(dp);

Output:./list_directoryexample_dir

contentsofthedirectoryexample_dirare

..

file1.txt

file2.txt

subdir1

subdir2

3. Programforsimulationofgrepunixcommands

Source code :
#include<stdio.h>
#include<string.h>
#define max 1024
void usage()
{
printf(“usage:\t./a.outfilenameword\n“);
}
intmain(intargc,char *argv[])
{
FILE *fp;
charfline[max];char*newline;intcount=0; int
occurrences=0; if(argc!=3)
{
usage();
exit(1);
}
if(!(fp=fopen(argv[1],”r”)))
{
printf(“grep:couldnotopenfile:%s\n”,argv[1]);
exit(1);
}
while(fgets(fline,max,fp)!=NULL)
{
count++;if(newline=strchr(fline,„\n‟))
*newline=‟\0‟;
if(strstr(fline,argv[2])!=NULL)
{
printf(“%s:%d%s\n”,argv[1],count,fline);
occurrences++;
}
}
}

InputandOutput:
Supposeyouhavea textfilenamedexample.txtwiththefollowingcontent: Hello
world!
Thisisatestfile.
Theword"test"appearstwiceinthistestfile. This
is the last line.

Input: ./search_word example.txt test


Output:example.txt:2Thisisatestfile.
example.txt:3Theword"test"appearstwiceinthistest file.

Experiment4:
Aim:SimulatethefollowingCPUschedulingalgorithms:
(a) Round Robin(b)SJF(c)FCFS (d)Priority
A) RoundRobinCPUSCHEDULINGALGORITHM
PROGRAM:
Sourcecode:
#include<stdio.h>
intmain()
{
int st[10],bt[10],wt[10],tat[10],n,tq;
inti,count=0,swt=0,stat=0,temp,sq=0;
float awt=0.0,atat=0.0;
printf("Enternumberofprocesses:");
scanf("%d",&n);
printf("Enterbursttimeforsequences:");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
st[i]=bt[i];
}
printf("Entertimequantum:");
scanf("%d",&tq);
while(1)
{
for(i=0,count=0;i<n;i++)
{
temp=tq;
if(st[i]==0)
{
count++;
continue;
}
if(st[i]>tq)
st[i]=st[i]-tq;
else
if(st[i]>=0)
{
temp=st[i];
st[i]=0;
}
sq=sq+temp;
tat[i]=sq;
}
if(n==count)
break;
}
for(i=0;i<n;i++)
{
wt[i]=tat[i]-bt[i];
swt=swt+wt[i];
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("Process_noBursttimeWaittimeTurnaroundtime");
for(i=0;i<n;i++)
printf("\n%d\t%d\t%d\t%d",i+1,bt[i],wt[i],tat[i]);
printf("\nAvgwaittimeis%fAvgturnaroundtimeis%f",awt,atat); return
0;
}
INPUT:
Enter number of processes:3
Enterbursttimeforsequences:12 8
20
Entertimequantum:5

EXPECTEDOUTPUT:
Process_noBursttimeWaittimeTurnaroundtime
1 12 1830
281523
3 20 2040
Avgwaittimeis17.666666Avgturnaroundtimeis31.000000

B) SJFCPUSCHEDULINGALGORITHM
PROGRAM:
Sourcecode:
#include<stdio.h>
intmain()
{
inti,j,bt[10],t,n,wt[10],tt[10],w1=0,t1=0;
float aw,at;
printf("enterno.ofprocesses:\n");
scanf("%d",&n);
printf("enterthebursttimeofprocesses:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
if(bt[i]>bt[j])
{
t=bt[i];
bt[i]=bt[j];
bt[j]=t;
}
}
for(i=0;i<n;i++)
printf("%d",bt[i]);
for(i=0;i<n;i++)
{
wt[0]=0;
tt[0]=bt[0];
wt[i+1]=bt[i]+wt[i];
tt[i+1]=tt[i]+bt[i+1];
w1=w1+wt[i];
t1=t1+tt[i];
}
aw=w1/n;
at=t1/n;
printf("\nbt\twt\ttt\n");
for(i=0;i<n;i++)
printf("%d\t%d\t%d\n",bt[i],wt[i],tt[i]);
printf("aw=%f\n,at=%f\n",aw,at);
return0;
}
INPUT:
enterno.ofprocesses:
3
enterthebursttimeofprocesses:12 8
20
EXPECTEDOUTPUT 8
12 20
btwttt
808
12820
20 20 40
aw=9.000000
,at=22.000000

C) FCFSCPUSCHEDULINGALGORITHM
PROGRAM:
Sourcecode:

#include<stdio.h>in
t main()
{
inti,j,bt[10],n,wt[10],tt[10],w1=0,t1=0;
float aw,at;
printf("enterno.ofprocesses:\n");
scanf("%d",&n);
printf("enterthebursttimeofprocesses:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
for(i=0;i<n;i++)
{
wt[0]=0;
tt[0]=bt[0];
wt[i+1]=bt[i]+wt[i];
tt[i+1]=tt[i]+bt[i+1];
w1=w1+wt[i];
t1=t1+tt[i];
}
aw=w1/n;
at=t1/n;
printf("\nbt\twt\ttt\n");
for(i=0;i<n;i++)
printf("%d\t%d\t%d\n",bt[i],wt[i],tt[i]);
printf("aw=%f\n,at=%f\n",aw,at);
return0;
}
INPUT:
enterno.ofprocesses:
3
enterthebursttimeofprocesses:12 8
20
EXPECTED OUTPUT:
btwttt
12012
81220
20 20 40
aw=10.000000
,at=24.000000

D) PrioritybasedCPUSCHEDULINGALGORITHM
PROGRAM:
Sourcecode:
#include<stdio.h>in
t main()
{
inti,j,pno[10],prior[10],bt[10],n,wt[10],tt[10],w1=0,t1=0,s;
float aw,at;
printf("enterthenumberofprocesses:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("The process %d:\n",i+1);
printf("Enterthebursttimeofprocesses:");
scanf("%d",&bt[i]);
printf("Enterthepriorityofprocesses%d:",i+1); scanf("%d",&prior[i]);
pno[i]=i+1;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(prior[i]<prior[j])
{
s=prior[i];
prior[i]=prior[j];
prior[j]=s;
s=bt[i];
bt[i]=bt[j];
bt[j]=s;
s=pno[i];
pno[i]=pno[j];
pno[j]=s;
}
}
}
for(i=0;i<n;i++)
{
wt[0]=0;
tt[0]=bt[0];
wt[i+1]=bt[i]+wt[i];
tt[i+1]=tt[i]+bt[i+1];
w1=w1+wt[i];
t1=t1+tt[i];
aw=w1/n;
at=t1/n;
}
printf("\njob\tbt\twt\ttat\tprior\n");
for(i=0;i<n;i++)
printf("%d\t%d\t%d\t%d\t%d\n",pno[i],bt[i],wt[i],tt[i],prior[i]);
printf("aw=%f \t at=%f \n",aw,at);
return0;
}
INPUT:
enterthenumberofprocesses:3
The process 1:
Enterthebursttimeofprocesses:12
Enter the priority of processes 1:3
The process 2:
Enterthebursttimeofprocesses:8
Enter thepriority of processes 2:2
The process 3:
Enterthebursttimeofprocesses:20
Enter the priority of processes 3:1
EXPECTED OUTPUT:
jobbtwttatprior 3
20 0 20 1
2820282
1 1228403
aw=16.000000at=29.000000

Experiment5:
Aim:Controlthenumberofportsopenedbytheoperatingsystem with
a. Semaphore
b. Monitor

A. Semaphore

#include<stdio.h>

#include <stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include <unistd.h>

#defineMAX_PORTS3
sem_tsemaphore;
void*open_port(void*arg){
intport_number=*((int*)arg);
printf("Thread%dwaitingtoopenaport...\n", port_number);

sem_wait(&semaphore);

printf("Thread%dopenedaport.\n",port_number);
sleep(2);

printf("Thread%dclosedtheport.\n",port_number);

sem_post(&semaphore);

free(arg);
returnNULL;
}

intmain(){
sem_init(&semaphore,0,MAX_PORTS);

pthread_tthreads[5];

for(int i=0;i<5;i++){
int*port_number = malloc(sizeof(int));
*port_number=i+1;
pthread_create(&threads[i],NULL,open_port,port_number);
}

for (int i = 0; i< 5; i++) {


pthread_join(threads[i],NULL);
}
sem_destroy(&semaphore);

return0;
}
Output:
Thread1waitingtoopenaport...
Thread 1 opened a port.
Thread2waitingtoopenaport...
Thread 2 opened a port.
Thread3waitingtoopenaport...
Thread 3 opened a port.
Thread4waitingtoopenaport...
Thread5waitingtoopenaport...
Thread 1 closed the port.
Thread 4 opened a port.
Thread2closedtheport.
Thread 5 opened a port.
Thread3closedtheport.
Thread4closedtheport.
Thread5closedtheport.

B. Monitors#include
<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include <unistd.h>

#defineMAX_PORTS 3

int open_ports = 0;
pthread_mutex_tmutex;
pthread_cond_tcond;
void*open_port(void*arg){
intport_number=*((int*)arg);
printf("Thread%dwaitingtoopenaport...\n",port_number);

pthread_mutex_lock(&mutex);

while(open_ports>=MAX_PORTS){
printf("Thread %d is waiting since all ports are busy.\n", port_number);
pthread_cond_wait(&cond,&mutex);//Blockthisthreaduntilthecondition is met
}

open_ports++;
printf("Thread%dopeneda port.Currentlyopenedports:%d\n",port_number,open_ports);

pthread_mutex_unlock(&mutex);

sleep(2);
pthread_mutex_lock(&mutex);

open_ports--;
printf("Thread%dclosedtheport. Currentlyopenedports:%d\n", port_number, open_ports);

pthread_cond_signal(&cond);

pthread_mutex_unlock(&mutex);

free(arg);
returnNULL;
}

int main() {
pthread_tthreads[5];
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond, NULL);

for(int i=0;i<5; i++){


int*port_number = malloc(sizeof(int));
*port_number=i+1;
pthread_create(&threads[i],NULL,open_port,port_number);
}

for (int i = 0; i< 5; i++) {


pthread_join(threads[i],NULL);
}

pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);

return0;
}

Output:
Thread1 waitingto openaport...
Thread1openeda port.Currentlyopenedports:1
Thread 2 waiting to open a port...
Thread2openeda port.Currentlyopenedports:2
Thread 3 waiting to open a port...
Thread3openeda port.Currentlyopenedports:3
Thread 4 waiting to open a port...
Thread4iswaitingsinceallportsarebusy.
Thread 5 waiting to open a port...
Thread5 is waitingsinceallports are busy.
Thread1closedtheport. Currentlyopenedports:2 Thread
4 opened a port. Currently opened ports: 3
Thread2closedtheport. Currentlyopenedports:2 Thread
5 opened a port. Currently opened ports: 3
Thread3closedtheport. Currentlyopenedports:2
Thread4closedtheport. Currentlyopenedports:1
Thread5closedtheport.Currentlyopenedports:0

ExperimentNo-6:

AIM:Writeaprogramtoillustrateconcurrentexecutionofthreadsusingpthreads
library.
SOURCECODE :
#include <stdio.h>
#include <stdlib.h>
#include<pthread.h>
#include <unistd.h>
#defineNUM_THREADS5
void*print_thread_info(void*threadid){
long tid;
tid= (long)threadid;
printf("Thread%ld:Starting...\n",tid);
sleep(1);
printf("Thread%ld:Exiting...\n",tid);
pthread_exit(NULL);
}
intmain(){
pthread_tthreads[NUM_THREADS];
int rc;
longt;

for(t=0;t <NUM_THREADS;t++){
printf("Main:Creatingthread%ld\n",t);
rc=pthread_create(&threads[t],NULL,print_thread_info,(void*)t); if
(rc) {
printf("Error:Unabletocreatethread%ld, %d\n", t,rc);
exit(-1);
}
}

for(t=0;t <NUM_THREADS;t++){
pthread_join(threads[t],NULL);
}
printf("Main:Allthreadscompleted.\n");
pthread_exit(NULL);
}
OUTPUT:
Main:creatingthread0
Main:creatingthread1
Main:creatingthread2
Main:creatingthread3
Main:creatingthread4
Thread 0 is starting...
Thread 1 is starting...
Thread 2 is starting...
Thread 3 is starting...
Thread 4 is starting...
Thread 0 is finishing...
Thread 1 is finishing...
Thread 2 is finishing...
Thread 3 is finishing...
Thread 4 is finishing...
Allthreadshavecompleted.

ExperimentNo-7:

AIM:Writeaprogramtosolveproducer-consumerproblemusingSemaphores.
SOURCE CODE :
#include <stdio.h>#include
<stdlib.h> #include
<pthread.h> #include
<semaphore.h> #include
<unistd.h>#define
BUFFER_SIZE 5
intbuffer[BUFFER_SIZE];
int count = 0;
sem_tempty;
sem_t full;
pthread_mutex_t mutex;

void*producer(void*arg){
int item;
while(1){
item = rand() % 100;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[count] = item;
count++;
printf("Produced:%d.Buffercount:%d\n",item,count);
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(rand()%2);//Sleepfor arandomtime
}
}
void*consumer(void*arg){
int item;
while (1) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
count--;
item=buffer[count];
printf("Consumed:%d.Buffercount:%d\n",item,count);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(rand() % 2);
}
}
intmain(){
pthread_tprod[3],cons[3];
sem_init(&empty,0,BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex,NULL);
for (int i = 0; i < 3; i++) {

pthread_create(&prod[i],NULL,producer,NULL);
}
for(int i=0;i<3; i++){
pthread_create(&cons[i],NULL,consumer,NULL);
}
for (int i = 0; i < 3; i++) {
pthread_join(prod[i], NULL);
pthread_join(cons[i],NULL);
}
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}

OUTPUT:
Producer1produced:12
Producer1produced:34
Producer2produced:45
Consumer1consumed:12
Consumer2consumed:34
Producer1produced:23
Consumer1consumed:45
Producer2produced:67
Consumer2consumed:23
Consumer1consumed:67
Producer1produced:89
Producer2produced:10
Consumer2consumed:89
Consumer1consumed:10
Producer1produced:5
Producer2produced:39
Consumer2consumed:5
Consumer1consumed:39

ExperimentNo-8:

AIM:Implementthefollowingmemoryallocationmethodsforfixedpartitiona)First fit b)
Worst fit c) Best fit
FirstFitMemoryAllocationSourceCode:
Source code :
#include<stdio.h>
voidfirstFit(int blocks[]
,intm,
intprocesses[],
int n) {
intallocation[n];
for(inti=0;i<n;i++){
allocation[i] = -1;
}
for(inti=0;i<n;i++){
for(intj=0;j<m;j++){
if(blocks[j]>=processes[i]){
allocation[i] = j;
blocks[j]-=processes[i];
break;
}
}
}
printf("FirstFitAllocation:\n");
for(inti=0;i<n;i++){ if
(allocation[i] != -1)
printf("Process %dallocatedtoBlock%d\n", i+1,allocation[i]+1); else
printf("Process%dnotallocated\n",i+1);
}
}
intmain(){
intblocks[]={100,500,200,300,600};
int processes[] = {212, 417, 112, 426};
intm=sizeof(blocks)/sizeof(blocks[0]);
intn=sizeof(processes)/sizeof(processes[0]);
firstFit(blocks, m, processes, n);
return0;
}

OUTPUT:
FirstFitAllocation:
Process1allocatedtoBlock2
Process2allocatedtoBlock5
Process3allocatedtoBlock2
Process 4 not allocated

B.BestFitMemoryAllocationSourcecode:
Source code:
#include<stdio.h>
voidbestFit(intblocks[],intm,intprocesses[],intn){ int
allocation[n];
for(inti=0;i<n;i++){
allocation[i]=-1;//Initializeallocationarray
}

for(inti=0;i<n;i++){
intbestIdx=-1;
for(intj=0;j<m;j++){
if(blocks[j]>=processes[i]){
if(bestIdx==-1||blocks[j]<blocks[bestIdx]){
bestIdx = j; // Select the smallest block that fits
}
}
}

if (bestIdx != -1) {
allocation[i]=bestIdx;
blocks[bestIdx]-=processes[i];
}
}

printf("BestFitAllocation:\n");
for (int i = 0; i< n; i++) {
if(allocation[i]!=-1)
printf("Process %dallocatedtoBlock%d\n", i+1,allocation[i]+1); else
printf("Process%dnotallocated\n",i+1);
}
}

intmain(){
int blocks[]={100,500, 200,300,600};//Memoryblocks
intprocesses[]={212,417,112,426};//Processesrequiringmemory int m

= sizeof(blocks) / sizeof(blocks[0]);
intn=sizeof(processes)/ sizeof(processes[0]);

bestFit(blocks,m,processes, n);
return0;
}

Output:
BestFitAllocation:
Process1allocatedtoBlock4
Process2allocatedtoBlock2
Process3allocatedtoBlock3
Process4allocatedtoBlock5

C. WorstFitMemoryAllocationSourceCode:

Source code:

#include<stdio.h>
voidworstFit(intblocks[],intm,intprocesses[],intn){ int
allocation[n];
for(inti=0;i<n;i++){
allocation[i]=-1;//Initializeallocationarray
}

for(inti=0;i<n;i++){ int
worstIdx = -1;
for(intj=0;j<m;j++){
if(blocks[j]>=processes[i]){
if(worstIdx==-1||blocks[j]>blocks[worstIdx]){
worstIdx = j; // Select the largest block that fits
}
}
}

if (worstIdx != -1) {
allocation[i]=worstIdx;
blocks[worstIdx]-=processes[i];
}
}

printf("Worst FitAllocation:\n");
for (int i = 0; i< n; i++) {
if(allocation[i]!=-1)
printf("Process %dallocatedtoBlock%d\n", i+1,allocation[i]+1); else
printf("Process%dnotallocated\n",i+1);
}
}
intmain(){
intblocks[]={100,500, 200,300,600};//Memoryblocks
intprocesses[]={212,417,112,426};//Processesrequiringmemory int m =
sizeof(blocks) / sizeof(blocks[0]);
intn=sizeof(processes)/sizeof(processes[0]);

worstFit(blocks, m, processes, n);

return0;
}
Output:
WorstFitAllocation:
Process1allocatedtoBlock5
Process2allocatedtoBlock2
Process3allocatedtoBlock5 Process
4 not allocated

ExperimentNo-9:

AIMSimulatethefollowingpagereplacementalgorithmsa)FIFOb)LRUc) LFU
a) FIFOSourceCode:
Source code:
#include<stdio.h>
voidfifoPageReplacement(intpages[],intn,intcapacity){ int
frames[capacity];
int front = 0, page_faults =
0;for(inti=0;i<capacity;i++)
frames[i] = -1;
printf("FIFOPageReplacement:\n");
for (int i = 0; i< n; i++) {
intpage=pages[i];
int flag = 0;
for(intj=0;j<capacity;j++){ if
(frames[j] == page) {
flag= 1;//Pagefound,nofault
break;
}
}
if(flag==0){
frames[front]=page;
front=(front+1)%capacity;
page_faults++;
printf("Page%dcausedapagefault.\n",page);
}
printf("Frames:[");
for(intj=0;j<capacity;j++){ if
(frames[j] != -1) {
printf("%d",frames[j]);
}else{
printf("- ");
}
}
printf("]\n");
}
printf("TotalPageFaults:%d\n\n",page_faults);
}

intmain(){
intpages[]={1,3, 0,3,5,6,3,1, 6,3};
intn=sizeof(pages)/sizeof(pages[0]); int
capacity = 3;
fifoPageReplacement(pages,n,capacity);
return 0;
}
Output:
Page1causedapagefault. Frames:
[1 - - ]
Page3causedapagefault. Frames:
[1 3 - ]
Page0causedapagefault. Frames:
[1 3 0 ]
Frames:[1 3 0]
Page5causedapagefault. Frames:
[5 3 0 ]
Page6causedapagefault. Frames:
[5 6 0 ]
Frames:[5 6 0]
Frames:[5 6 0]
Frames:[5 6 0]
TotalPageFaults:5

b) LRUSourceCode:
Source code :
#include<stdio.h>

voidlruPageReplacement(intpages[],
int n,
intcapacity)
{
intframes[capacity],counter[capacity],time=0; int

page_faults = 0;
for(inti=0;i<capacity;i++){
frames[i] = -1;
counter[i]=0;
}
printf("LRUPageReplacement:\n");
for (int i = 0; i< n; i++) {
int page = pages[i];
intflag=0,least=0;
for(intj=0;j<capacity;j++){ if
(frames[j] == page) {
flag= 1;//Pagefound,nofault
counter[j]=++time;//UpdatetimeforLRU
break;
}
}
if(flag==0){//Pagefaultoccurred for
(int j = 1; j < capacity; j++) {
if(counter[j]<counter[least]){
least = j;
}
}
frames[least]=page;//Replacetheleastrecentlyusedpage
counter[least] = ++time;// Update time
page_faults++;
printf("Page%dcausedapagefault.\n",page);
}
printf("Frames:[");
for(intj=0;j<capacity;j++){ if
(frames[j] != -1) {
printf("%d",frames[j]);
}else{
printf("- ");
}
}
printf("]\n");
}
printf("TotalPageFaults:%d\n\n",page_faults);
}
intmain(){
intpages[]={1,3, 0,3,5,6,3,1, 6,3};
intn=sizeof(pages)/sizeof(pages[0]); int
capacity = 3;
lruPageReplacement(pages,n,capacity);
return 0;
}
OUTPUT:
Page1causedapagefault. Frames:
[1 - - ]
Page3causedapagefault. Frames:
[1 3 - ]
Page0causedapagefault. Frames:
[1 3 0 ]
Frames:[1 3 0]
Page5causedapagefault. Frames:
[5 3 0 ]
Page6causedapagefault. Frames:
[5 6 0 ]
Frames:[5 6 0]
Frames:[5 6 0]
Frames:[5 6 0]
TotalPageFaults:5

c) LFUSourceCode:
Sourcecode:
#include<stdio.h>
voidlfuPageReplacement(intpages[],
int n,
intcapacity)
{
intframes[capacity],frequency[capacity],page_faults=0; for
(int i = 0; i< capacity; i++) {
frames[i]=-1;
frequency[i]=0;
}
printf("LFUPageReplacement:\n");
for (int i = 0; i< n; i++) {
intpage= pages[i];
intflag=0,least=0;
for(intj=0;j<capacity;j++){ if
(frames[j] == page) {
flag= 1;//Pagefound,nofault
frequency[j]++;//Increasefrequencyofthe page
break;
}
}
if(flag== 0){//Pagefaultoccurred
for(intj=1;j<capacity;j++){ if
(frequency[j] < frequency[least]) {
least=j;
}
}
frames[least]=page;//Replacetheleastfrequentlyusedpage frequency[least] =
1;// Reset the frequency for the new page
page_faults++;
printf("Page%dcausedapagefault.\n",page);
}
printf("Frames:[");
for(intj=0;j<capacity;j++){ if
(frames[j] != -1) {
printf("%d",frames[j]);
}else{
printf("- ");
}
}
printf("]\n");
}
printf("TotalPageFaults:%d\n\n",page_faults);
}
intmain(){
intpages[]={1,3, 0,3,5,6,3,1, 6,3};
intn=sizeof(pages)/sizeof(pages[0]); int
capacity = 3;
lfuPageReplacement(pages,n,capacity);
return 0;
}
Output:
Page1causedapagefault. Frames:
[1 - - ]
Page3causedapagefault. Frames:
[1 3 - ]
Page0causedapagefault. Frames:
[1 3 0 ]
Frames:[1 3 0]
Page5causedapagefault. Frames:
[5 3 0 ]
Page6causedapagefault. Frames:
[5 6 0 ]
Frames:[5 6 0]
Frames:[5 60]
Frames: [5 6 0 ]
TotalPageFaults:5

ExperimentNo:10
Aim:SimulatePagingTechniqueofmemorymanagement.
Source Code:
#include <stdio.h>
#include <stdlib.h>
#definePAGE_SIZE4
#defineMEMORY_SIZE16
#defineNUM_PAGESMEMORY_SIZE/PAGE_SIZE
intmain(){
intlogical_address,page_number,offset,physical_address; int
page_table[NUM_PAGES];
for(inti=0;i<NUM_PAGES;i++){

page_table[i] = i;
}
printf("PAGETABLE:\n");
printf("PageNumber->FrameNumber\n"); for
(int i = 0; i < NUM_PAGES; i++) {
printf(" %d -> %d\n",i, page_table[i]);
}
printf("\nEnteralogicaladdress(0to%d):",MEMORY_SIZE-1);
scanf("%d", &logical_address);
if(logical_address<0||logical_address>=MEMORY_SIZE){
printf("Invalidlogicaladdress!Pleaseenter anaddressbetween0and%d.\n", MEMORY_SIZE
-1);
return1;
}
page_number=logical_address/PAGE_SIZE;
offset = logical_address % PAGE_SIZE;
physical_address=(page_table[page_number]*PAGE_SIZE)+offset;
printf("\nLogical Address: %d\n", logical_address);
printf("PageNumber:%d,Offset:%d\n",page_number,offset);
printf("PhysicalAddress:%d(FrameNumber:%d,Offset:%d)\n",physical_address,
page_table[page_number], offset);

return0;
}

Output:
PAGETABLE:
PageNumber->FrameNumber
0 -> 0
1 -> 1
2 -> 2
3 -> 3

Enter alogicaladdress(0to15):6

LogicalAddress: 6
PageNumber:1,Offset:2
PhysicalAddress:6(FrameNumber:1,Offset:2)

ExperimentNo:11
Aim:ImplementBankersAlgorithmforDeadLockavoidanceandprevention Source
Code:
#include <stdio.h>
#include<stdbool.h>
#define P 5
#defineR3
boolisSafe(intprocesses[],intavail[],intmax[][R],intalloc[][R],intneed[][R]){ int
work[R], finish[P] = {0};
for (inti=0;i<R;i++){ work[i]
= avail[i];
}
intsafeSeq[P];
int count =
0;while(count<P){
boolfound= false;
for(int p=0;p<P; p++){
if(!finish[p]){//Ifprocessisnotfinished bool
possible = true;
for(intj= 0;j<R;j++){
if(need[p][j]>work[j]){
possible = false;
break;
}
}
if(possible){
for (intk=0;k<R;k++){ work[k]
+= alloc[p][k];
}
safeSeq[count++]=p;
finish[p] = 1;
found=true;
}
}
}

if (!found) {
returnfalse;
}
}
printf("Systemisina safestate.\nSafesequenceis:"); for
(int i = 0; i < P; i++) {
printf("%d",safeSeq[i]);
}
printf("\n");
return true;
}

intmain(){
intprocesses[P]={0, 1,2,3, 4};
intavail[R]={3,3,2};
intmax[P][R]={{7,5, 3},
{3,2,2},
{9,0,2},
{2,2,2},
{4,3, 3}};
intalloc[P][R]={{0,1, 0},
{2,0,0},
{3,0,2},
{2,1,1},
{0,0,2}};

intneed[P][R];
for (int i = 0; i < P; i++) {
for (intj=0;j<R;j++){
need[i][j]= max[i][j]-alloc[i][j];
}
}

if(!isSafe(processes,avail,max,alloc,need)){
printf("System is not in a safe state.\n");
}

return0;
}

Output:
System is in a safe state.
Safesequenceis:13402
ExperimentNo:12
Aim:Simulatethefollowingfileallocation strategiesa) Sequentialb)Linked c)Indexed

a) SequentialAllocationSourceCode:

#include<stdio.h>
#defineMAX_BLOCKS100
int blocks[MAX_BLOCKS];
voidsequentialAllocation(intstartBlock,intfileSize){ int
i;
for(i=startBlock;i<(startBlock+fileSize);i++){ if
(blocks[i] == 1) {
printf("Block%disalreadyallocated.Sequentialallocationfailed.\n",i); return;
}
}
for(i=startBlock;i<(startBlock+fileSize);i++){ blocks[i] =
1;
}
printf("FileallocatedusingSequentialAllocationfromblock%dtoblock%d.\n", startBlock,
startBlock + fileSize - 1);
}

intmain(){
intstartBlock,fileSize;
for(inti=0;i<MAX_BLOCKS;i++){
blocks[i] = 0;
}
printf("Enter thestartingblockandfilesize:");
scanf("%d%d", &startBlock, &fileSize);
sequentialAllocation(startBlock, fileSize);
return0;
}

Output:
Enter thestartingblockandfilesize:5 3
FileallocatedusingSequentialAllocationfromblock5toblock 7.

b) LinkedallocationSourceCode:

#include<stdio.h>
#defineMAX_BLOCKS100
struct Block {
int nextBlock;
intisAllocated;
};
structBlockblocks[MAX_BLOCKS];
voidlinkedAllocation(intstartBlock,intfileSize){ int
count = 0, currentBlock = startBlock;

while(count<fileSize){
if(blocks[currentBlock].isAllocated==1){
printf("Block%disalreadyallocated.Linkedallocationfailed.\n",currentBlock);
return;
}
blocks[currentBlock].isAllocated=1;
if (count <fileSize - 1) {
printf("Enterthenextblocknumberafter%d:",currentBlock);
scanf("%d", &blocks[currentBlock].nextBlock);
currentBlock=blocks[currentBlock].nextBlock;
}else{
blocks[currentBlock].nextBlock=-1;//Endoffile
}
count++;
}
printf("FileallocatedusingLinkedAllocationstartingfromblock%d.\n",startBlock);
}
intmain(){
intstartBlock,fileSize;
for(inti=0;i<MAX_BLOCKS;i++){
blocks[i].isAllocated = 0;
blocks[i].nextBlock=-1;
}
printf("Enter thestartingblockandfilesize:");
scanf("%d%d", &startBlock, &fileSize);
linkedAllocation(startBlock, fileSize);
return0;
}

Output:
Enter thestartingblockandfilesize:33
Enter the next block number after 3: 5
Enter the next block number after 5: 7

FileallocatedusingLinkedAllocationstartingfromblock 3.

c) IndexedAllocationSourceCode:

#include<stdio.h>
#defineMAX_BLOCKS100
#defineMAX_INDEX_SIZE10
int blocks[MAX_BLOCKS];
int indexBlock[MAX_INDEX_SIZE];
voidindexedAllocation(intindexBlockNo,intfileSize){ int
i, dataBlock;
for(i=0;i<MAX_INDEX_SIZE;i++){
indexBlock[i]=-1;
}
printf("Entertheblocknumbers tostorethefile data:\n")
for(i=0;i<fileSize;i++){
scanf("%d", &dataBlock);
if(blocks[dataBlock]==1){
printf("Block%disalreadyallocated.Indexedallocationfailed.\n",dataBlock); return;
}
blocks[dataBlock]=1;
indexBlock[i] = dataBlock;
}
printf("FileallocatedusingIndexedAllocation. Indexblockisatblock%d.\n", indexBlockNo);
printf("Index block contents: ");
for(i=0;i<fileSize;i++){
printf("%d ", indexBlock[i]);
}
printf("\n");
}
intmain(){
intindexBlockNo,fileSize;
for(inti=0;i<MAX_BLOCKS;i++){ blocks[i] =
0;
}
printf("Entertheindexblocknumberandfilesize:");
scanf("%d%d", &indexBlockNo, &fileSize);
indexedAllocation(indexBlockNo, fileSize);
return0;
}

Output:
Enter theindexblocknumber andfilesize:23 Enter
the block numbers to store the file data:
579
FileallocatedusingIndexedAllocation. Indexblockisatblock2. Index
block contents: 5 7 9
ExperimentNo:13
Aim:Downloadandinstallnachosoperatingsystemandexperimentwith it
NACHOS (Not Another Completely Heuristic Operating System) is a pedagogical operating system
designed for educational purposes. It allows students to implement and experiment with various
operating system functionalities, including process management, memory management, file systems,
and synchronization.

1. InstallPrerequisites
Opentheterminalandrunthefollowingcommandto installtherequiredpackages: sudo
apt update
sudoaptinstallbuild-essentialgcc g++git

2. DownloadNACHOSSourceCode

downloadNACHOSfromtheStanfordNACHOSpageChange
into the downloaded directory:
cd nachos
3. CompileNACHOS

Navigatetothecodedirectoryandcompilethesourcecode: cd
code
makeclean
make
4. RunNACHOS

RunNACHOStoformatthefilesystem:
./nachos-f

Executea sampleprogram:

./nachos-x../test/halt

You might also like