OS LAB R 23
OS LAB R 23
&
ENGG.&TECH
GARIVIDI
VizianagaramDist(AP)
Estd 2001
2025-2026
LABORATORY MANUAL
OF
Prepared by
1. Institute Vision & Mission, Department Vision & Mission Institute Vision:
To produce Competent Engineering Graduates & Managers with a strong base of Technical &
Managerial Knowledge and the Complementary Skills needed to be Successful Professional
Engineers & Managers.
Institute Mission: To fulfill the vision by imparting Quality Technical & Management
Education to the Aspiring Students, by creating Effective Teaching/Learning Environment and
providing State – of the – Art Infrastructure and Resources.
Department Vision: To produce Industry ready Software Engineers to meet the challenges of
21st Century.
Department Mission:
Impart core knowledge and necessary skills in Computer Science and Engineering through
innovative teaching and learning methodology.
Inculcate critical thinking, ethics, lifelong learning and creativity needed for industry and
society.
Cultivate the students with all-round competencies, for career, higher education and
self- employ-ability .
Course Objectives:
The main objectives of the course are to
Provide insights into system calls, file systems, semaphores,
Develop and debug CPU Scheduling algorithms, page replacement algorithms, thread
implementation.
Implement Banker’s Algorithms to Avoid the Dead Lock.
Course Outcomes:
cd Command :
cd command is used to change the directory.
cd linux-command
This command will take you to the sub-directory(linux -command) from its parent
directory.
Ex:
cd ..
This will change to the parent-directory from the current working directory/sub-
directory.
cd ~
This command will move to the user's home directory which is "/home/username".
cat Command
The cat command is a multi-purpose utility in the Linux system. It can be used to create a file,
display content of the file, copy the content of one file to another file, and more.
Syntax:
1. cat [OPTION]... [FILE]..
To create a file, execute it as follows:
1. cat ><file name>
2. // Enter file content
Press "CTRL+ D" keys to save the file. To display the content of the file, execute
it as follows:
1. cat <file name>
Output:
rm command:
ls command:
ls command liststhe files and directories under current working directory. Display root
directory contents: ls / Lists the contents of root directory.
Display hidden files and directories: ls -a lists all entries including hidden files and directories.
Display inode information: ls –I
Output:
mkdir command: Use this command to create one or more new directories.
Include one or more instances of the “<DIRECTORY” variable (separating each
with a white space), and set each to the complete path to the new directory to be
created.
mkdir OPTION <DIRECTORY>
rmdir Command
The rmdir command is used to delete a directory.
Syntax:
1. rmdir <directory name>
mv command:
The mv command is used to move a file or a directory form one location to
another location.
Syntax:
1. mv <file name><directory path>
Output:
ps Command:
ps command is used to report the process status. ps is the short name for Process
Status.
$ ps # show process info
$ ps -f # : Displays full information about currently running processes.
man Command
The "man" is a short term for manual page. In unix like operating systems such
as linux, man is an interface to view the system's reference manual.
A user can request to display a man page by simply typing man followed by a
space and then argument. Here its argument can be a command, utility or
function.
A manual page associated with each of these arguments is displayed
Syntax of man:
man [option(s)] keyword(s)
But generally [option(s)] are not used. Only keyword is written as an argument.
For example,
1. man ls
This command will display all the information about 'ls' command as shown in the
Picture.
who
The who command gives the information about the users logged on to the system.
Syntax:
1. who
pwd Command
The pwd command is used to display the location of the current working directory.
Syntax:
1. pwd
Output:
touch – Create an empty file or update the timestamp of an existing file:
touch file_name
find – Find files by name in the current directory:
find . -name "filename"
grep – Search text within files
Search for a specific word inside a file:grep "word" file_name
Search for a word in all files in the current directory: grep -r "word" .
cal Command
The cal command is used to display the current month's calendar with the
current date highlighted.
Syntax:
1. cal<
Output:
time Command:
The time command is used to display the time to execute a command.
Syntax:
1. time
Output:
echo
The echo command in Linux is a built built-in
in command that allows users to display lines of text or
strings that are passed as arguments. It is commonly used in shell scripts and batch files to
output status text to the screen or a file.
Syntax of `echo` command
mmand in Linux
echo [option] [string]
Here,
[options] = The various options available for modifying the behavior of the `echo` command
[string] = It is the string that we want to display.
Option Description
Displays a help message with information about the echo command and its
--help
options.
finger
The ‘finger’ command is a powerful utility in Linux used to display information about users
logged into the system. This command is commonly used by system administrators to retrieve
detailed user information, including login name, full name, idle time, login time, and sometimes
the user’s email address. The ‘finger’
finger’ command offers more comprehensive details compared to
the ‘pinky’ command, which is a lighter version with limited output.
Syntax: $sudo apt-get install finger
Logout
Logout command allows you to programmatically logout from your session. causes the
session manager to take the requested action immediately.
Syntax:$logout
Example:
Shutdown
The `shutdown` operation in Linux is a crucial command for managing system power states,
allowing administrators to halt safely, power off, or reboot the system. This command provides
flexibility in scheduling downtimes, ensuring minimal disruption to users and processes. In this
article, we will explore the `shutdown` command with practical examples, illustrating how to use
its various options to control system behavior effectively.
Syntax:
shutdown [OPTIONS] [TIME] [MESSAGE]
OPTIONS:: Various options to control the shutdown process, such as halting, powering
off, or rebooting the system.
TIME: Specifies
ies when to perform the shutdown, either immediately, after a specified
delay, or at a specific time.
MESSAGE:: An optional message that is broadcasted to all logged
logged-in
in users, informing
them of the scheduled shutdown.
Key Options of the Shutdown Command
The following are the options of shutdown command in Linux:
‘-r’: Requests that the system be rebooted after it has been brought down.
‘-h’: Requests that the system be either halted or powered off after it has been brought down,
with the choice as to which left up to the system.
‘-H’: Requests that the system be halted after it has been brought down.
‘-P’: Requests that the system be powered off after it has been brought down.
‘-c’: Cancels a running shutdown. TIME is not specified with this option, the first argument is
MESSAGE.
‘-k’: Only send out the warning messages and disable logins, do not actually bring the system
down.
EXPERIMENT 2
Aim: Write programs using the following UNIX operating system calls fork, exec, getpid, exit,
wait, close, stat, opendir and readdir.
1. fork() - Create a child process
Source Code:
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
// Error
perror("fork failed");
return 1;
}
if (pid == 0) {
// Child process
printf("This is the child process with PID: %d\n", getpid());
} else {
// Parent process
printf("This is the parent process with PID: %d\n", getpid());
}
return 0;
}
Expected Output:
Source Code:
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// Child process
printf("Child process before exec\n");
execlp("/bin/ls", "ls", "-l", NULL);
// This line won't be executed if exec() is successful
perror("exec failed");
} else if (pid > 0) {
// Parent process
Expected Output:
Source Code:
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = getpid();
printf("The process ID is: %d\n", pid);
return 0;
}
Expected Output:
Source Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("This is the main process.\n");
exit(0); // Exit with a status code of 0
printf("This line won't be printed.\n");
}
Expected Output:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// Child process
printf("Child process is running.\n");
sleep(2); // Simulate some work
printf("Child process finished.\n");
return 0;
} else if (pid > 0) {
// Parent process
printf("Parent process waiting for child to finish.\n");
wait(NULL); // Wait for child process to terminate
printf("Parent process finished.\n");
} else {
perror("fork failed");
}
return 0;
}
Expected Output:
Source Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("test.txt", O_CREAT | O_WRONLY, 0666);
if (fd == -1) {
perror("Error opening file");
return 1;
}
write(fd, "Hello, World!\n", 14);
close(fd); // Close the file descriptor
printf("File closed successfully.\n");
Source Code:
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
struct stat fileStat;
if (stat("test.txt", &fileStat) == -1) {
perror("Error getting file status");
return 1;
}
printf("File size: %ld bytes\n", fileStat.st_size);
printf("Last modified: %ld\n", fileStat.st_mtime);
return 0;
}
Expected Output:
Source Code:
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
if (dir == NULL) {
perror("Error opening directory");
return 1;
}
printf("Listing files in the current directory:\n");
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
Expected Output:
sql
Copy
Listing files in the current directory:
.
..
test.txt
program.c
Source Code:
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
if (dir == NULL) {
perror("Error opening directory");
return 1;
}
printf("Files and directories in the current directory:\n");
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
Expected Output:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
void copy_file(const char *source, const char *destination) {
int src_fd = open(source, O_RDONLY);
if (src_fd == -1) {
perror("Error opening source file");
return;
Expected Output:
Source Code:
#include <stdio.h>
#include <string.h>
void grep_pattern(const char *filename, const char *pattern) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return;
}
char line[1024];
int line_number = 1;
while (fgets(line, sizeof(line), file)) {
if (strstr(line, pattern)) {
Expected Output:
(if "hello" is in the file)
Source Code:
#include <stdio.h>
void cat_file(const char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
}
int main() {
const char *filename = "file1.txt";
cat_file(filename);
return 0;
}
Expected Output:
(assuming file1.txt contains some text):
This is the content of file1.txt.
It has multiple lines.
Source Code:
#include <stdio.h>
#include <stdlib.h>
void remove_file(const char *filename) {
if (remove(filename) == 0) {
printf("File '%s' deleted successfully.\n", filename);
} else {
perror("Error deleting file");
}
}
int main() {
const char *filename = "file1.txt";
remove_file(filename);
return 0;
}
Expected Output:
Source Code:
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
void create_directory(const char *dir_name) {
if (mkdir(dir_name, 0777) == 0) {
printf("Directory '%s' created successfully.\n", dir_name);
} else {
perror("Error creating directory");
}
}
int main() {
const char *dir_name = "new_folder";
create_directory(dir_name);
return 0;
}
Source Code:
#include <stdio.h>
#include <unistd.h>
int main() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working directory: %s\n", cwd);
} else {
perror("Error getting current directory");
}
return 0;
}
Expected Output:
Current working directory: /home/user/Documents
INPUT
Enterthe number of processes -- 3
Enter Burst Time for Process 0 -- 24
Enter Burst Time for Process 1 -- 3
Enter Burst Time for Process 2 -- 3
OUTPUT
For SJF scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times.
Arrange all the jobs in order with respect to their burst times. There may be two jobs in queue with the
same execution time, and then FCFS approach is to be performed. Each process will be executed
according to the length of its burst time. Then calculate the waiting time and turnaround time of each
of the processes accordingly.
Source Code:
#include<stdio.h>
#include<conio.h>
main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
clrscr();
printf("\n Enter the number of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i]; bt[i]=bt[k]; bt[k]=temp;
}
np=p[i];p[i]=p[k]; p[k]=temp;
wt[0]=wtavg=0;
}
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
INPUT
Enter the number of processes -- 4
Enter Burst Time for Process 0 -- 6
Enter Burst Time for Process 1 -- 8
Enter Burst Time for Process 2 -- 7
Enter Burst Time for Process 3 -- 3
OUTPUT:
For priority scheduling algorithm, read the number of processes/jobs in the system, their CPU burst
times, and the priorities. Arrange all the jobs in order with respect to their priorities. There may be two
jobs in queue with the same priority, and then FCFS approach is to be performed. Each process will be
executed according to its priority. Calculate the waiting time and turnaround time of each of the
processes accordingly.
Source Code:
#include<stdio.h>main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp;float wtavg, tatavg;
clrscr();
printf("Enter the number of processes --- ");scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i);scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k])
{
temp=p[i];p[i]=p[k]; p[k]=temp;
temp=bt[i]; bt[i]=bt[k]; bt[k]=temp;
temp=pri[i]; pri[i]=pri[k];pri[k]=temp;
}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\n PROCESS \t\t PRIORITY \t BURST TIME \t WAITING TIME \t TURNAROUND
TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\n Average Waiting Time is --- %f",wtavg/n);
INPUT
Enter the number of processes --5
Enter the Burst Time &Priority of Process 0 --- 10
Enter the Burst Time & Priority of Process 1 --- 1
Enter the Burst Time & Priority of Process 2 --- 2
Enter the Burst Time & Priority of Process 3 --- 1
Enter the Burst Time & Priority of Process 4 --- 5
OUTPUT
PROCESS PRIORITY BURST TIME WAITING TIME TURNAROUND TIME
1 1 1 0 1
4 2 5 1 6
0 3 10 6 16
2 4 2 16 18
3 5 1 18 19
Average Waiting Time is --- 8.200000
Average Turnaround Time is --- 12.000000
Source Code:
#include<stdio.h>
main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;float awt=0,att=0,temp=0;
clrscr();
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\n Enter the size of time slice -- ");
scanf("%d",&t);
max=bu[0]; for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t; temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];att+=tat[i];
awt+=wa[i];
}
INPUT
OUTPUT
Aim: Write a c program the number of ports opened by the operating system with
Semaphore
Semaphore: A synchronization primitive that is used to control access to a shared
resource by multiple processes in a concurrent system. It is typically used to restrict
the number of processes that can access a resource concurrently. In this case, we can
use a semaphore to limit the number of open ports.
Source Code:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAX_PORTS 3 // Maximum number of open ports
sem_t port_semaphore; // Semaphore to control the number of open ports
void* open_port(void* arg) {
int process_id = *((int*)arg);
printf("Process %d trying to open a port...\n", process_id); // Wait for a free port
sem_wait(&port_semaphore);
printf("Process %d opened a port.\n", process_id);
sleep(2); // Simulating port usage for 2 seconds // Release the port
printf("Process %d closed the port.\n", process_id);
sem_post(&port_semaphore);
return NULL;
}
int main() {
pthread_t processes[5];
int process_ids[5] = {1, 2, 3, 4, 5};
// Initialize semaphore with MAX_PORTS available
sem_init(&port_semaphore, 0, MAX_PORTS); //Create 5 processes to simulate port opening
for (int i = 0; i < 5; i++) {
pthread_create(&processes[i], NULL, open_port, &process_ids[i]);
}
// Wait for all threads to finish
for (int i = 0; i < 5; i++) {
pthread_join(processes[i], NULL);
}
Expected Output:
Process 1 trying to open a port...
Process 1 opened a port.
Process 2 trying to open a port...
Process 2 opened a port.
Process 3 trying to open a port...
Process 3 opened a port.
Process 4 trying to open a port...
Process 4 is waiting for a free port.
Process 5 trying to open a port...
Process 5 is waiting for a free port.
Process 1 closed the port.
Process 4 opened a port.
Process 2 closed the port.
Process 5 opened a port.
Process 3 closed the port.
Process 4 closed the port.
Process 5 closed the port.
Source Code:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void* print_thread_info(void* arg) {
// Get the thread ID using pthread_self()
pthread_t thread_id = pthread_self();
// Print the thread ID
printf("Thread ID: %lu is executing\n", (unsigned long)thread_id);
// Simulate some work being done by sleeping for 2 seconds
sleep(2);
printf("Thread ID: %lu has finished execution\n", (unsigned long)thread_id);
return NULL;
}
int main() {
pthread_t threads[5]; // Array to hold thread identifiers
// Create 5 threads
for (int i = 0; i < 5; i++) {
if (pthread_create(&threads[i], NULL, print_thread_info, NULL) != 0) {
perror("Thread creation failed");
return 1;
}
}
// Wait for all threads to finish
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
printf("All threads have finished execution\n");
return 0;
}
Expected Output:
Thread ID: 140438428383744 is executing
Thread ID: 140438419991040 is executing
Thread ID: 140438411598336 is executing
Thread ID: 140438403205632 is executing
Thread ID: 140438394812928 is executing
Thread ID: 140438428383744 has finished execution
Thread ID: 140438419991040 has finished execution
Thread ID: 140438411598336 has finished execution
Thread ID: 140438403205632 has finished execution
Thread ID: 140438394812928 has finished execution
All threads have finished execution
DESCRIPTION :
Producer-consumer problem, is a common paradigm for cooperating processes. A producer
process produces information that is consumed by a consumer process. One solution to the
producer-consumer problem uses shared memory. To allow producer and consumer processes
to run concurrently, there must be available a buffer of items that can be filled by the producer
and emptied by the consumer. This buffer will reside in a region of memory that is shared by
the producer and consumer processes. A producer can produce one item while the consumer is
consuming another item. The producer and consumer must be synchronized, so that the
consumer does not try to consume an item that has not yet been produced.
Source Code:
#include<stdio.h>
void main()
{
int buffer[10], bufsize, in, out, produce, consume, choice=0;in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf(“\n1. Produce \t 2. Consume \t3. Exit”);printf(“\nEnter your choice: ”);
scanf(“%d”,&choice);
}
switch(choice)
case 1: if((in+1)%bufsize==out)
printf(“\n Buffer is Full”);
else
{
printf(“\nEnter the value: “);
scanf(“%d”, &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
Break;
case 2: if(in == out)
printf(“\n Buffer is Empty”);
else
{
consume = buffer[out];
printf(“\n The consumed value is %d”, consume);out = (out+1)%bufsize;
}
Break;
}
OUTPUT
OUTPUT
2. Produce 2. Consume 3. Exit Enter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. Exit Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit Enter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. Exit Enter your choice: 3
The Memory Allocation Problem is a common problem in operating systems where we need
to assign memory blocks to processes. The three common techniques for fixed partition
memory allocation are:
1. First Fit
2. Worst Fit
3. Best Fit
First Fit: Allocates the first available memory block that is large enough to hold the process.
Worst Fit: Allocates the largest available memory block that is large enough to hold the
process.
Best Fit: Allocates the smallest available memory block that is large enough to hold the
process, leaving the smallest leftover fragment.
Source Code:
#include <stdio.h>
#define MEMORY_BLOCKS 10 // Number of memory blocks
#define PROCESSES 5 // Number of processes
// Function to implement First Fit memory allocation
void first_fit(int memory[], int block_size[], int processes[], int process_size[]) {
printf("\n First Fit Memory Allocation:\n");
for (int i = 0; i < PROCESSES; i++) {
int allocated = 0;
for (int j = 0; j < MEMORY_BLOCKS; j++) {
if (memory[j] == 0 && block_size[j] >= process_size[i]) {
// Allocate memory
memory[j] = process_size[i];
printf("Process %d of size %d allocated to block %d of size %d\n", i + 1,
process_size[i], j + 1, block_size[j]);
allocated = 1;
break;
}
}
if (!allocated) {
printf("Process %d of size %d could not be allocated\n", i + 1, process_size[i]);
}
}
}
// Function to implement Worst Fit memory allocation
void worst_fit(int memory[], int block_size[], int processes[], int process_size[]) {
printf("\n Worst Fit Memory Allocation:\n");
return 0;
}
Explanation:
The function first_fit checks each memory block in the order they appear. The first block that
is large enough to fit the process is allocated.
The function worst_fit looks for the largest block that is large enough to accommodate the
process. If multiple blocks are available, it chooses the one with the largest remaining space
after allocation.
The function best_fit looks for the smallest block that can still accommodate the process. It
aims to minimize wasted space by selecting the block with the smallest leftover space after
allocation.
Memory Initialization:
The array memory keeps track of the allocated memory. Initially, all entries are set to 0,
indicating that the blocks are unallocated.
The block_size array represents the sizes of the memory blocks available.
The process_size array contains the sizes of the processes that need to be allocated to the
memory blocks.
Function Calls:
The main function calls each of the three allocation methods: first_fit, worst_fit, and best_fit,
with appropriate resetting of the memory between calls to simulate independent allocation
methods.
Expected Output:
DESCRIPTION
Page replacement is basic to demand paging. It completes the separation between logical
memory and physical memory. With this mechanism, an enormous virtual memory can be
provided for programmers on a smaller physical memory. There are many different page-
replacement algorithms.
Every operating system probably has its own replacement scheme. A FIFO replacement
algorithm associates with each page the time when that page was brought into memory. When
a page must be replaced, the oldest page is chosen. If the recent past is used as an
approximation of the near future, then the page that has not been used for the longest period of
time can be replaced. This approach is the Least Recently Used (LRU) algorithm. LRU
replacement associates with each page the time of that page's last use. When a page must be
replaced, LRU chooses the page that has not been used for the longest period of time. Least
frequently used (LFU) page-replacement algorithm requires that the page with the smallest
count be replaced. The reason for this selection is that an actively used page should have a
large reference count.
Source Code:
#include<stdio.h>
#include<conio.h>main()
{
int i, j, k, f, pf=0, count=0, rs[25], m[10], n;
clrscr();
printf("\n Enter the length of reference string -- ");
scanf("%d",&n);
printf("\n Enter the reference string -- ");
for(i=0;i<n;i++)
scanf("%d",&rs[i]);
printf("\n Enter no. of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
m[i]=-1;
printf("\n The Page Replacement Process is -- \n");
for(i=0;i<n;i++)
{
for(k=0;k<f;k++)
{
}
if(k==f)
{
INPUT:
Enter the length of reference string – 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter no. of frames -- 3
OUTPUT
Source Code:
#include<stdio.h>
int main()
{
int m, n, position, k, l;
int a = 0, b = 0, page_fault = 0;
int total_frames = 3;
int frames[total_frames];
int temp[total_frames];
int pages[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3, 6, 1, 2, 4, 3};
int total_pages = sizeof(pages)/sizeof(pages[0]);
for(m = 0; m < total_frames; m++){
frames[m] = -1;
}
for(n = 0; n < total_pages; n++)
{
printf("%d: ", pages[n]);
a = 0, b = 0;
for(m = 0; m < total_frames; m++)
{
if(frames[m] == pages[n])
{
a = 1;
b = 1;
break;
}
}
if(a == 0)
{
for(m = 0; m < total_frames; m++)
{
if(frames[m] == -1)
{
frames[m] = pages[n];
b = 1;
page_fault++;
break;
}
}
}
if(b == 0)
{
for(m = 0; m < total_frames; m++)
{
temp[m] = 0;
}
for(k = n - 1, l = 1; l <= total_frames - 1; l++, k--)
return 0;
}
Output –
1: 1 -1 -1
2: 1 2 -1
3: 1 2 3
2: 1 2 3
1: 1 2 3
5: 1 2 5
2: 1 2 5
1: 1 2 5
6: 1 2 6
2: 1 2 6
5: 5 2 6
6: 5 2 6
3: 5 3 6
1: 1 3 6
3: 1 3 6
6: 1 3 6
1: 1 3 6
2: 1 2 6
4: 1 2 4
3: 3 2 4
Total Number of Page Faults: 11
Source Code:
#include<stdio.h>
void print(int frameno,int frame[])
{
int j;
for(j=0;j<frameno;j++)
printf("%d\t",frame[j]);
printf("\n");
}
int main()
{
int i,j,k,n,page[50],frameno,frame[10],move=0,flag,count=0,count1[10]={0},
repindex,leastcount;
float rate;
printf("Enter the number of pages\n");
scanf("%d",&n);
printf("Enter the page reference numbers\n");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter the number of frames\n");
scanf("%d",&frameno);
for(i=0;i<frameno;i++)
frame[i]=-1;
printf("Page reference string\tFrames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t\t",page[i]);
flag=0;
for(j=0;j<frameno;j++)
{
frame[repindex]=page[i];
count1[repindex]=1;
count++;
Source Code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int size,m,n,pgno,pagetable[3]={5,6,7},i,j,frameno;
double m1;
int ra=0,ofs;
clrscr();
printf(“Enter process size (in KB of max 12KB):”); /*reading memeory size*/
scanf(“%d”,&size);
m1=size/4;
n=ceil(m1);
printf(“Total No. of pages: %d”,n);
printf(“\n Enter relative address (in hexadecimal notation eg.0XRA) \n”);
//printf(“The length of relative Address is : 16 bits \n\n The size of offset is :12 bits\n”);
scanf(“%d”,&ra);
pgno=ra/1000; /*calculating physical address*/
ofs=ra%1000;
printf(“page no=%d\n”,pgno);
printf(“page table”);
for(i=0;i<n;i++)
printf(“\n %d [%d]”,i,pagetable[i]);
frameno=pagetable[pgno];
printf(“\n Equivalent physical address : %d%d”,frameno,ofs);
getch();
}
AIM:. Implement Bankers Algorithm for Dead Lock avoidance and prevention
Source Code:
#include<stdio.h>
int main() {
/* array will store at most 5 process with 3 resoures if your process or
resources is greater than 5 and 3 then increase the size of array */
int p, c, count = 0, i, j, alc[5][3], max[5][3], need[5][3], safe[5], available[3], done[5],
terminate = 0;
printf("Enter the number of process and resources");
scanf("%d %d", & p, & c);
// p is process and c is diffrent resources
printf("enter allocation of resource of all process %dx%d matrix", p, c);
for (i = 0; i < p; i++) {
for (j = 0; j < c; j++) {
scanf("%d", & alc[i][j]);
}
}
printf("enter the max resource process required %dx%d matrix", p, c);
for (i = 0; i < p; i++) {
for (j = 0; j < c; j++) {
scanf("%d", & max[i][j]);
}
}
printf("enter the available resource");
for (i = 0; i < c; i++)
scanf("%d", & available[i]);
}
if (terminate != (p - 1)) {
printf("\n available resource after completion\n");
for (i = 0; i < c; i++) {
printf("%d\t", available[i]);
}
printf("\n safe sequence are\n");
for (i = 0; i < p; i++) {
printf("p%d\t", safe[i]);
}
}
return 0;
}
a) Sequential
b) Indexed
c) Linked
Source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DISK_SIZE 10 // Size of the disk (number of blocks)
// Sequential Allocation
void sequentialAllocation(char disk[], int disk_size, char file, int file_size) {
int start_block = -1;
if (can_allocate) {
start_block = i;
break;
}
}
// Indexed Allocation
void indexedAllocation(char disk[], int disk_size, char file, int file_size) {
int index_block = -1;
// Linked Allocation
void linkedAllocation(char disk[], int disk_size, char file, int file_size) {
int last_block = -1;
int allocated_blocks[file_size];
int main() {
char disk[DISK_SIZE] = {0}; // 0 indicates free block, non-zero values are allocated blocks
char file;
int file_size;
// Sequential Allocation
printf("Sequential Allocation:\n");
sequentialAllocation(disk, DISK_SIZE, 'A', 3);
// Indexed Allocation
printf("Indexed Allocation:\n");
indexedAllocation(disk, DISK_SIZE, 'B', 2);
displayDisk(disk, DISK_SIZE);
// Linked Allocation
printf("Linked Allocation:\n");
linkedAllocation(disk, DISK_SIZE, 'C', 4);
displayDisk(disk, DISK_SIZE);
IZE);
return 0;
}
OUTPUT: