N200030 (OS Lab)
N200030 (OS Lab)
LAB-01
FILE SYSTEM CALLS
Aim: Introduction to system calls–Implementation of open(), create(),close(), write(), read(),
lseek().
SystemCalls:System calls are fundamental interfaces between an application and the operating
system. They allow programs to request services from the kernel, such as file manipulation,
process control, and communication.
Name: Open()
Description:Opens a file for reading, writing, or both.
. pathname: Path to the file to open.
· flags: Flags that determine the file access mode (e.g., O_RDONLY, O_WRONLY, O_RDWR).
· mode: File permissions (used when creating a new file).
Syntax: int open(const char *pathname, int flags, mode_t mode);
Program:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
int main(){
int fd;
fd=open("non.txt",O_RDONL
Y);if(fd == -1){perror("open");
return 1;}
printf("file opened successfully with file description %d",fd);
close(fd);
Output:
Name: create()
Description :Creates a new file or rewrites an existing one
.pathname: Path to the file to create.
. mode: File permissions.
Syntax: int creat(const char *pathname, mode_t mode);
Program:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
int main(){ int fd;
fd=creat("non.txt", 0600);
if(fd == -1){perror("creat");
return 1;}
printf("file created successfully with file description %d",fd);close(fd);}
Name: write()
Description:Writes data to an open filefd:
File descriptor of the file to write to.
buf: Buffer containing data to write.
count: Number of bytes to write
Syntax: ssize_t write(int fd, const void *buf, size_t count);
Program:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
int main(){ int fd;
const char *text="Hello,world!";
ssize_t bytes_written;
fd=open("non.txt",O_WRONLY|O_CREAT,060
0);
if(fd==-1){ perror("open"); return 1;}
bytes_written=write(fd,text,12);
if(bytes_written==-1){
perror(write);close(fd);
return 1; }
printf("Successfully wrote %ld bytes to the file",bytes_written);
close(fd); }
Output:
Name: read()
Description:Reads data from an open file.
· fd: File descriptor of the file to read from.
· buf: Buffer where read data will be stored.
· count: Number of bytes to read.
Syntax:ssize_t read(int fd, void *buf, size_t count);
Program:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
int main(){ int fd;
char buffer[100];
ssize_t bytes_read;
fd=open("non.txt",O_RDONL
Y);
if(fd == -1){perror("open");
return 1;}
bytes_read=read(fd,buffer,sizeof(buffer)-1);
if(bytes_read==-1){ perror("read");
close(fd); return 1;}
buffer[bytes_read]='\0';
Operating systems Laboratory 2
N200030 Yeddula Sai Harshitha
printf("read %ld bytes: %s",bytes_read,buffer);}
Output:
Name: lseek()
Description:Repositions the file offset.
· fd: File descriptor of the file.
· offset: New position relative to whence.
· whence: Position from which offset is applied (SEEK_SET, SEEK_CUR, SEEK_END).
Syntax: off_t lseek(int fd, off_t offset, int whence);
Program:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
int main(){ int fd;
off_t offset;
fd=open("non.txt",O_RDONL
Y);if(fd == -1){perror("open");
return 1; }
offset=lseek(fd,5,SEEK_SE
T);if(offset==-1){
perror("lseek");
close(fd); return 1; }
printf("seked to position: %ld",offset);
close(fd); }
Output:
Name: close()
Description:Closes an open file descriptor.fd:
File descriptor to close.
Syntax:int close(int fd);
Program:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
int main(){ int fd;
fd=open("non.txt",O_
RDONLY);
if(fd ==1){
perror("creat");
return 1;}
if(close(fd)== -1){
perror("close");
return 1; }
printf("file closed successfully ");}
Output:
LAB-02
PROCESS SYSTEM CALLS
Aim:- Study and implement the Process System Calls fork() , exec() , wait() , kill()
using C Language.
1) Name: fork()
Return Value:
o On success, the PID of the child process is returned in the parent, and 0
is returned in the child.
o On failure, -1 is returned in the parent, no child process is created, and
errno is set appropriately.
C program:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid1, pid2;
int status1, status2;
pid1 = fork();
if (pid1 == 0) {
printf("Child 1 PID: %d, Parent PID: %d\n", getpid(), getppid());
pid2 = fork();
if (pid2 == 0) {
printf("Child 2 PID: %d, Parent PID: %d\n", getpid(), getppid());
sleep(2);
printf("Child 2 exiting\n");
_exit(0);
} else if (pid2 > 0) {
wait(&status2); // Wait for Child 2 to finish
printf("Child 1 exiting\n");
_exit(0);
} else {
perror("Second fork failed");
_exit(1);
}
} else if (pid1 > 0) {
wait(&status1); // Wait for Child 1 to finish
printf("Parent process exiting\n");
} else {
return 0;
}
OUTPUT:-
Description: The exec() system call in Unix-like operating systems replaces the
current process image with a new process image loaded from the specified executable
file. It loads the program into the current process space, replacing the existing
program. The original process attributes such as file descriptors and process ID
remain intact for the new process.
3)Name: wait()
Description: The wait() system call in Unix-like operating systems suspends the
execution of the calling process until one of its child processes terminates. It allows
the parent process to synchronize with the termination of its child processes and
obtain information about their exit status.
Syntax: pid_t wait(int *status);
Parameters:
o status: Pointer to an integer where the exit status of the child process
will be stored.
Return Value:
o Returns the process ID of the terminated child process on success, or -
1 on failure. The exit status of the child process is stored in the integer
pointed to by status.
C program :
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include
<sys/types.h>#include <sys/wait.h>
int main(int argc, char **argv){
pid_t pid; // Variable to store process ID
pid = fork()
if (pid < 0){
perror("fork failed");
exit(EXIT_FAILURE);}
else if (pid == 0{
printf("This is the child process with PID %d\n", getpid());
printf("The parent's PID is %d\n", getppid());
exit(0);}
else{
printf("This is the parent process with PID %d\n", getpid());
printf("The child's PID is %d\n", pid);
int status;
pid_t child_pid = wait(&status);
if (child_pid == -1) {
perror("wait failed");
exit(EXIT_FAILURE); }
printf("Child process with PID %d exited with status %d\n", child_pid, status);}
return 0;}
OUTPUT:-
3)Name: kill()
Description: The kill() system call in Unix-like operating systems sends a signal to a
process or a group of processes. It allows processes to communicate with each other
by sending specific signals that can trigger actions like termination, interruption, or
other handling based on the signal type.
Syntax: int kill(pid_t pid, int sig);
Parameters:
o pid: Process ID of the process to which the signal is to be sent.
o sig: Signal number to send.
Return Value:
o Returns 0 on success, or -1 on failure. errno is set to indicate the error.
C program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
void signal_handler(int sig) {
printf("Received signal %d\n", sig);}
int main(int argc, char **argv){
pid_t pid = getpid(); // Get the current process ID
if (signal(SIGUSR1, signal_handler) == SIG_ERR) {
perror("signal");
return EXIT_FAILURE; }
if (kill(pid, SIGUSR1) == -1) {
perror("kill failed");
return EXIT_FAILURE;}
printf("Sent SIGUSR1 signal to process with PID %d\n", pid);
sleep(1);
return 0;}
OUTPUT:-
LAB-03
SCHEDULING ALGORITHMS
Aim : Implementation of FCFS(first come first serve) non-preeemptive and
SJF(shortest job first) with preemptive and non-preemptive scheduling algorithms.
Name : First Come First Serve(FCFS)
Description : FCFS is a simple scheduling algorithm where the process that arrives
first gets executed first.It’s a non-preemptive meaning once a process starts it runs to
completion before the next one starts.
Input :
#include <stdio.h>
void main(){
int n,i,j,temp;
float total_wt,total_tat;
printf("Enter no.of processes : ");
scanf("%d",&n);
int pro[n],arr[n],burst[n],gantt[n+1],wt[n],tat[n];
for(i=0;i<n;i++){ pro[i]=i+1;
printf("Enter arrival time for Process %d : ",i+1);
scanf("%d",&arr[i]);}
for(i=0;i<n;i++){ printf("Enter burst time for Process %d : ",i+1);
scanf("%d",&burst[i]);}
printf("\nProcess\tArrival Time\tBurst Time\n");
printf("-------------------------------\n");
for (i=0;i<n;i++) {
printf("P%d\t%d\t\t%d\n", pro[i], arr[i], burst[i]);}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(arr[i]<arr[j] || (arr[i]==arr[j] && pro[i]<pro[j])){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
temp=burst[i];
burst[i]=burst[j];
burst[j]=temp;
temp=pro[i];
pro[i]=pro[j];
pro[j]=temp;}
}}
gantt[0]=arr[0];
gantt[1]=burst[0];
for(i=2;i<=n;i++){
if(gantt[i-1]<=arr[i-1]){
gantt[i]=arr[i-1]+burst[i-1];}
else
gantt[i]=gantt[i-1]+burst[i-1];}
printf("\nGantt Chart\n");
printf("-------------------------------\n");
for(i=0;i<n;i++){printf(" P%d\t",pro[i]);}
printf("\n");
for(i=0;i<=n;i++){ printf("%d\t",gantt[i]);}
printf("\n-------------------------------\n");
for(i=0;i<=n;i++){
if(i>=1){ tat[i-1]=gantt[i]-arr[i-1];}}
for(i=0;i<n;i++){ wt[i]=tat[i]-burst[i];}
printf("Process\tTurnaroundtime\tWaitingtime\t\n");
for(i=0;i<n;i++){
printf("P%d\t%d\t\t\t%d\n",pro[i],tat[i],wt[i]);
total_tat=tat[i]+total_tat;
total_wt=wt[i]+total_wt;}
printf("Average waiting time : %.2f ms\n",total_wt/n);
printf("Average turnaroundtime : %.2f ms",total_tat/n); }
Output :
hr=arr[0];
for(i=0;i<n;i++){
if(arr[i]>hr){ hr=arr[i]; }}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(arr[i]<arr[j] || (arr[i]==arr[j] && pro[i]<pro[j])){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
temp=burst[i];
burst[i]=burst[j];
burst[j]=temp;
temp=pro[i];
pro[i]=pro[j];
pro[j]=temp;}}}
for(i=0;i<n;i++)
if(arr[i]==0) c=c+1;
if(c==n){
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(burst[i]<burst[j]){
temp=burst[i];
burst[i]=burst[j];
burst[j]=temp;
temp=pro[i];
pro[i]=pro[j];
pro[j]=temp;}}}}
gantt[0]=arr[0];
gantt[1]=burst[0];
for(i=2;i<=n;i++){
if(gantt[i-1]>hr){
for(j=i-1;j<n;j++){
for(k=i-1;k<n;k++){
if(burst[j]<burst[k]){
temp=burst[j];
burst[j]=burst[k];
burst[k]=temp;
temp=pro[j];
pro[j]=pro[k];
pro[k]=temp;
temp=arr[j];
arr[j]=arr[k];
arr[k]=temp;}}}}
if(gantt[i-1]<=arr[i-1]){ gantt[i]=arr[i-1]+burst[i-1];}
else{ gantt[i]=gantt[i-1]+burst[i-1];} }
printf("\nGantt Chart\n");
printf("-------------------------------\n");
for(i=0;i<n;i++){ printf(" P%d\t",pro[i]);}
printf("\n");
for(i=0;i<=n;i++){
printf("%d\t",gantt[i]);}
printf("\n-------------------------------\n");
for(i=0;i<=n;i++){
if(i>=1){
tat[i-1]=gantt[i]-arr[i-1];}}
for(i=0;i<n;i++){
wt[i]=tat[i]-burst[i];}
printf("Process\tTurnaroundtime\tWaitingtime\t\n");
for(i=0;i<n;i++){
printf("P%d\t%d\t\t\t%d\n",pro[i],tat[i],wt[i]);
total_tat=tat[i]+total_tat;
total_wt=wt[i]+total_wt; }
printf("Average waiting time : %.2f ms\n",total_wt/n);
printf("Average turnaroundtime : %.2f ms",total_tat/n); }
Output:
for(i=0;i<n;i++){ db[i]=burst[i];}
for(i=0;i<n;i++){ vis[i]=0;}
printf("-------------------------------\n");
for (i=0;i<n;i++) {
printf("P%d\t%d\t\t%d\n", pro[i], arr[i], burst[i]);}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(arr[i]<arr[j] || (arr[i]==arr[j] && pro[i]<pro[j])){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
temp=burst[i];
burst[i]=burst[j];
burst[j]=temp;
temp=pro[i];
pro[i]=pro[j];
pro[j]=temp;}}}
hr=arr[0];
for(i=0;i<n;i++){
if(arr[i]>hr){ hr=arr[i];}}
gantt[0]=arr[0];
gantt[1]=arr[1];
db[0]=burst[0]-gantt[1];
vis[0]=1;
up[0]=0;
up[1]=1;
s=n;
for(i=1;i<s;i++){
mb=db[i];
for(j=0;j<n;j++){
if(vis[j]==1 && db[j]<mb && db[j]!=0){ mb=db[j];}}
sm=db[0];
for(h=0;h<n;h++){
if(db[h]<sm && db[h]>0){sm=db[h];}}
db[i]=mb-(arr[i+1]-arr[i]);
if(sm==db[i] || mb==sm){
gantt[i+1]=gantt[i]+mb;
up[i]=i;
db[i]=0;
vis[i]=1;}
else if(gantt[i]>hr){
gantt[i+1]=gantt[i]+db[i];
up[i]=i;
db[i]=0;
vis[i]=1;}
else{ gantt[i+1]=gantt[i]+burst[i];
up[i]=i;
db[i]=0;
vis[i]=1;}}
for(i=0;i<n;i++){
if(db[i]>0){ g=g+1;
mb=db[i];
for(j=0;j<n;j++){
if(db[i]<mb){ mb=db[i];}}}
gantt[n+i+1]=gantt[n+i]+db[i];
printf("\nGantt Chart\n");
printf("-------------------------------\n");
for(i=0;i<g;i++){
printf(" P%d\t",up[i]);}
printf("\n");
for(i=0;i<=g;i++){
printf("%d\t",gantt[i]);}
printf("\n-------------------------------\n"); }
int l=0;
for(i=0;i<n;i++){
for(j=0;j<g;j++){
if(up[j]==l){ mb=j;}}
l=l+1;
tat[i]=gantt[mb+1]-arr[i];
for(h=0;h<n;h++){
if(up[h]==h){ nn[h]=gantt[h+1]-gantt[h];}}
if(i==0){
wt[i]=gantt[mb]-nn[i]-arr[i];}
else{ wt[i]=gantt[mb]-arr[i];}}
for(i=0;i<n;i++){
total_wt=total_wt+wt[i];
total_tat=total_tat+tat[i];}
printf("Average Waitingtime : %.2f\n",total_wt/n);
printf("Average turnaroundtime : %.2f",total_tat/n);}
Output:
LAB-04
PRIORITY, RR SCHEDULING ALGORITHM
Aim:To implement proirity preemptive,non-preemptive scheduling algorithms,round-
robin scheduling algorithms.
1.Name : Priority non-preemetive
Description : Priority non-preemptive scheduling is a CPU scheduling algorithm
where processes are selected based on their priority level,with higher priority
processes being executed first.Once a process starts executing,it runs to completion
without being interrupted by other processes,even if a higher priority process arrives.
Input:
#include <stdio.h>
void main(){
int n,i,j,temp,mp,mb;
printf("Enter no.of processes : ");
scanf("%d",&n);
int pro[n],gantt[n+1],arr[n],burst[n],pri[n],h,s,vis[n],tat[n],wt[n],f;
float total_tat=0,total_wt=0;
for(i=0;i<n;i++){
pro[i]=i+1;}
for(i=0;i<n;i++){
printf("Enter arrival time for process : ",i+1);
scanf("%d",&arr[i]);}
for(i=0;i<n;i++){
printf("Enter burst time for process %d : ",i+1);
scanf("%d",&burst[i]);}
for(i=0;i<n;i++){
printf("Enter priority for process %d : ",i+1);
scanf("%d",&pri[i]);}
printf("\nProcess\tArrivaltime\tBursttime\tPriority\n");
printf("------------------------------------------------\n");
for (i=0;i<n;i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", pro[i], arr[i], burst[i],pri[i]);}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(arr[i]<arr[j] || ((arr[i]==arr[j]) && i<j)){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
temp=pro[i];
pro[i]=pro[j];
pro[j]=temp;
temp=burst[i];
burst[i]=burst[j];
burst[j]=temp;
temp=pri[i];
pri[i]=pri[j];
pri[j]=temp;}}}
gantt[0]=arr[0];
gantt[1]=burst[0];
pro[0]=1;
for(i=0;i<n;i++){ vis[i]=0;}
vis[0]=1;
mp=pri[0];
for(i=1;i<n;i++){
mb=burst[i-1];
for(j=1;j<n;j++) {
mp=1e9;
h=-1; }
for(j=0;j<n;j++){
if(arr[j]<=gantt[i] && vis[j]==0 && pri[j]<mp){
mp=pri[j];
h=j;}}
printf("\n");
if (h!=-1) {
vis[h]=1;
pro[i]=h+1;
gantt[i+1]=gantt[i]+burst[h];
}}
printf("------------------------------------\n");
printf("\n");
for(i=0;i<n;i++){
printf(" P%d\t",pro[i]);}
printf("\n");
for(i=0;i<=n;i++){
printf("%d\t",gantt[i]);}
printf("\n------------------------------------\n");
for(i=1;i<=n;i++){
f=pro[i-1]-1;
tat[i-1]=gantt[i]-arr[f];
wt[i-1]=tat[i-1]-burst[f];
total_tat+=tat[i-1];
total_wt+=wt[i-1];}
printf("Average waiting time : %.2f ms\n",total_wt/n);
printf("Average turnaroundtime : %.2f ms",total_tat/n);}
Output:
2.Name:Priority Preemptive
Description:Priority preemptive scheduling is a CPU scheduling algorithm are
selected based on priority processes preempting lower priority ones if they arrive
while another process is running.
Input:
#include <stdio.h>
#include <limits.h>
void main() {
int n, i, j, time = 0, remain;
int pro[20], arr[20], burst[20], pri[20], vis[20], remaining_burst[20];
int tat[20], wt[20], current_proc = -1;
float total_tat = 0, total_wt = 0;
int gantt[40], gantt_proc[20], gantt_index = 0, start_time;
printf("Enter number of processes: ");
scanf("%d", &n);
remain = n;
for (i = 0; i < n; i++) {
printf("Enter arrival time for process %d: ", i + 1);
scanf("%d", &arr[i]);}
for (i = 0; i < n; i++) {
printf("Enter burst time for process %d: ", i + 1);
scanf("%d", &burst[i]);}
for (i = 0; i < n; i++) {
printf("Enter priority for process %d: ", i + 1);
scanf("%d", &pri[i]);
pro[i] = i + 1;
vis[i] = 0;
remaining_burst[i] = burst[i];}
printf("\nProcess\tArrival Time\tBurst Time\tPriority\n");
printf("------------------------------------------------\n");
for (i = 0; i < n; i++) {
printf("P%d\t%d\t\t%d\t\t%d\n", pro[i], arr[i], burst[i], pri[i]);}
printf("\nGantt Chart:\n");
printf("------------------------------------------------\n");
while (remain > 0) {
int min_pri = INT_MAX;
int min_index = -1;
for (i = 0; i < n; i++) {
if (arr[i] <= time && vis[i] == 0 && pri[i] < min_pri) {
min_pri = pri[i];
min_index = i;}}
if (min_index != -1) {
if (current_proc != min_index) {
if (current_proc != -1 && remaining_burst[current_proc] > 0) {
gantt[gantt_index] = time;
gantt_proc[gantt_index] = pro[current_proc];
gantt_index++;}
current_proc = min_index;
start_time = time;}
time++;
remaining_burst[current_proc]--;
if (remaining_burst[current_proc] == 0) {
vis[current_proc] = 1;
remain--;
3.Name : Round-Robin
Description : Round Robin is a CPU scheduling algorithm where each process is
assigned a fixed time slot (time quantum) in a cyclic order.If a process is not
completed within its time slot,it is placed back in the queue,and the next process is
executed.
Input:
#include <stdio.h>
void main() {
int n, tq, time = 0, remaining_processes, flag = 0,i;
printf("Enter number of processes: ");
scanf("%d", &n);
remaining_processes= n;
int arrival[n], burst[n], remaining[n], completion[n], waiting[n], turnaround[n];
for (i=0;i<n;i++){
printf("Enter arrival time for process %d: ",i+1);
scanf("%d", &arrival[i]);}
for(i=0;i<n;i++){
printf("Enter burst time for process %d: ",i+1);
scanf("%d",&burst[i]);
remaining[i] = burst[i];
completion[i] = 0;}
printf("Enter time quantum: ");
scanf("%d", &tq);
printf("\nGantt Chart:\n");
while (remaining_processes != 0) {
for (i=0;i<n;i++){
if (arrival[i] <= time && remaining[i] > 0) {
if (remaining[i] > tq) {
printf("| P%d %d-%d ", i + 1, time, time + tq);
time += tq;
remaining[i] -= tq;}
else { printf("| P%d %d-%d ", i + 1, time, time + remaining[i]);
time += remaining[i];
remaining[i] = 0;
remaining_processes--;
completion[i] = time;}
flag = 1;}}
if (flag == 0) time++;
else{ flag = 0;}}
printf("|\n");
for (i = 0; i < n; i++) {
turnaround[i] = completion[i] - arrival[i];
waiting[i] = turnaround[i] - burst[i];}
printf("\nCompletion times:\n");
for (i = 0; i < n; i++) printf("P%d: %d\n", i + 1, completion[i]);
printf("\nTurnaround times:\n");
float avgturnaround=0;
for (i = 0; i < n; i++) {
avgturnaround+=turnaround[i];
printf("P%d: %d\n", i + 1, turnaround[i]);}
printf("\n average turnaround time %f \n",avgturnaround/n);
printf("\nWaiting times:\n");
float avgwaiting=0;
for (i = 0; i < n; i++) {
avgwaiting+=waiting[i];
printf("P%d: %d\n", i + 1, waiting[i]);}
printf("\n average waiting time %f\n",avgwaiting/n); }
Output:
LAB-05
PRODUCER CONSUMER PROBLEM-SOLUTION
Aim:Implement producer-consumer problem using semaphore in C also in
java(Multithreading).
A) Producer-consumer problem in C
Description:The producer-consmer problem is a classic synchronization issue where
a producer generates data and a consumer processes it.The challenge is to ensure they
don’t accessa shared resource(like a buffer) simultaneously,preventing data corruption
or resource underflow/overflow.
Input:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE,in = 0,out = 0;
sem_t empty,full;
pthread_mutex_t mutex;
void *producer(void *arg) {
int item,i;
for ( i = 0; i < 20; i++) {
item = rand() % 100; // Produce an item
sem_wait(&empty); // Decrease empty count
pthread_mutex_lock(&mutex); // Enter critical section
buffer[in] = item; // Put item in buffer
printf("Producer produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // Leave critical section
sem_post(&full); // Increase full count}
return NULL;}
void *consumer(void *arg) {
int item,i;
for (i = 0; i < 20; i++) {
sem_wait(&full); // Decrease full count
pthread_mutex_lock(&mutex); // Enter critical section
item = buffer[out]; // Remove item from buffer
printf("Consumer consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // Leave critical section
sem_post(&empty); // Increase empty count}
return NULL;}
int main() {
pthread_t prod, cons;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;}
Output:
LAB-06
BANKER’S ALGORITHM
Banker’s safety algorithm:-
Description:- Before granting a resource request, the system checks if it will remain
in a safe state after allocation.
· A state is considered safe if there is a sequence of processes where each process can
obtain its maximum resources, execute, and then release the resources, allowing the
next process in the sequence to proceed.
Program:-
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXPRO 20
#define MAXRES 20
void bankers_algorithm(int np,int nr,int allocation[MAXPRO][MAXRES],int
max[MAXPRO][MAXRES],int available[MAXRES]);
int main() {
int np, nr;
printf("Enter number of processes and resources respectively: ");
scanf("%d %d", &np, &nr);
int allocation[MAXPRO][MAXRES], max[MAXPRO][MAXRES],
available[MAXRES];
printf("Enter the Allocation Matrix:\n");
for (int i = 0; i < np; i++) {
for (int j = 0; j < nr; j++) {scanf("%d", &allocation[i][j]);}}
printf("Enter the Max Matrix:\n");
for (int i = 0; i < np; i++) {
for (int j = 0; j < nr; j++) {scanf("%d", &max[i][j]);}}
printf("Enter the Available Matrix:\n");
for (int i = 0; i < nr; i++) {scanf("%d", &available[i]);}
bankers_algorithm(np, nr, allocation, max, available);return 0;}
void bankers_algorithm(int np, int nr, int allocation[MAXPRO][MAXRES], int
max[MAXPRO][MAXRES], int available[MAXRES]) {
int need[MAXPRO][MAXRES];
for (int i = 0; i < np; i++) {
for (int j = 0; j < nr; j++) {need[i][j] = max[i][j] - allocation[i][j];} }
bool finish[MAXPRO] = {false};
int safeSequence[MAXPRO], work[MAXRES];
for (int i = 0; i < nr; i++) {work[i] = available[i];}
int count = 0,j;
while (count < np) {
bool found = false;
for (int i = 0; i < np; i++) {if (!finish[i]) {
for (j = 0; j < nr; j++) {if (need[i][j] > work[j]) {break; }}
if (j == nr) { // If all needs are satisfied
for (int k = 0; k < nr; k++) {work[k] += allocation[i][k];}
safeSequence[count++] = i;finish[i] = true;found = true;}}}
if (!found) {printf("The system is not in a safe state.");}}
printf("The system is in a safe state.\nSafe sequence is: ");
for (int i = 0; i < np; i++) {printf("%d ", safeSequence[i]+1);}printf("\n"); }
OUTPUT:-
LAB-07
PARTITION ALGORITHMS
Aim:- write a C programs for the Partition Algorithms,
A) . First Fit
B) Best Fit
C) Worst Fit
First Fit Algorithm
Description:- The First Fit algorithm allocates memory to the first available block
large enough to satisfy the request. It searches from the beginning of the memory list
and stops as soon as a suitable free block is found.
C Program:-
#include <stdio.h>
#define MAX 100
void firstFit(int blocks[], int blockCount, int processes[], int processCount) {
int allocation[MAX];
for (int i = 0; i < processCount; i++) allocation[i] = -1;
for (int i = 0; i < processCount; i++) {
for (int j = 0; j < blockCount; j++) {
if (blocks[j] >= processes[i]) { allocation[i] = j;
blocks[j] -= processes[i];break;}}}
printf("First-Fit Allocation:\n");
for (int i = 0; i < processCount; i++) { if (allocation[i] != -1)
printf("Process %d allocated to Block %d\n", i + 1, allocation[i] + 1);
else printf("Process %d not allocated\n", i + 1); }}
int main() { int blockCount, processCount, blocks[MAX], processes[MAX];
printf("Enter the number of memory blocks: ");
scanf("%d", &blockCount);
printf("Enter the sizes of the memory blocks:\n");
for (int i = 0; i < blockCount; i++) scanf("%d", &blocks[i]);
printf("Enter the number of processes: ");
scanf("%d", &processCount);
printf("Enter the sizes of the processes:\n");
for (int i = 0; i < processCount; i++) scanf("%d", &processes[i]);
firstFit(blocks, blockCount, processes, processCount);
return 0;}
Output:-
LAB-8
Aim:write a c program to implement paging such as finding page table size and
maximum page
table entry size
Description:Paging is a memory management scheme that eliminates the need for
contiguous
allocation of physical memory, thereby minimizing fragmentation and allowing for
efficient use of
memory.formulas used:
1)If number of bits in virtual address space is “x” then process size is ” 2 x ”
2) No of entries or pages=process size/page size
3)Page table size=no of entries * page table entry size
4)Max page table entry size=page size/number of entries.
Program for finding page table size:
#include <stdio.h>
#include <math.h>
int main() {
unsigned int processBits;char pageSizeUnit, entrySizeUnit;
double pageSize, pageTableEntrySize, pageTableSizeMB;
unsigned long long processSize, numEntries;
printf("Enter process bits: ");
scanf("%u", &processBits);
printf("Enter page size only value not units: ");
scanf("%lf", &pageSize);
printf("Enter page size unit (B for Bytes, K for KB, M for MB): ");
scanf(" %c", &pageSizeUnit);
switch (pageSizeUnit) {
case 'K':
case 'k':pageSize *= 1024; break;
case 'M':
case 'm':pageSize *= 1024 * 1024;break;
case 'B':
case 'b'://already in bytes
default:break;}
printf("Enter page table entry size only value not units: ");
scanf("%lf", &pageTableEntrySize);
printf("Enter page table entry size unit (B for Bytes, K for KB, M for MB): ");
scanf(" %c", &entrySizeUnit);
switch (entrySizeUnit) {
case 'K':case 'k':pageTableEntrySize *= 1024;break;
case 'M':case 'm':pageTableEntrySize *= 1024 * 1024;break;
case 'B':case 'b':
default:break;}
processSize = pow(2, processBits);numEntries = processSize / pageSize;
unsigned long long pageTableSize = numEntries * pageTableEntrySize;
pageTableSizeMB = (double) pageTableSize / (1024 * 1024);
printf("Page table size: %.2f MB\n", pageTableSizeMB);
return 0;}
Output:
LAB-09
PAGE REPLACEMENT ALGORITHMS
Aim:- write a C programs for the Page Replacment Algorithms,
A) FIFO
B) LRU
FIFO Algorithm
Description:- The FIFO (First-In, First-Out) page replacement algorithm replaces the
oldest page in memory when a new page needs to be loaded. It follows a simple queue
structure, removing pages in the order they were loaded.
C Program:-
#include <stdio.h>
void FIFO(int pages[], int n, int frames) {
int frame[frames], faults = 0, front = 0, flag, i, j;
for (i = 0; i < frames; ++i) frame[i] = -1;
printf("\nPage\tFrames\n");
for (i = 0; i < n; ++i) { flag = 0;
for (j = 0; j < frames; ++j) {
if (frame[j] == pages[i]) {
flag = 1;
break;}}
if (flag == 0) { frame[front] = pages[i];
front = (front + 1) % frames;
faults++; }
printf("%d\t", pages[i]);
for (j = 0; j < frames; ++j) {
if (frame[j] != -1) {
printf("%d ", frame[j]); }
else { printf("- "); }}
printf("\n"); }
printf("\nTotal Page Faults = %d\n", faults); }
int main() {
int n, frames, i;
printf("Enter number of pages: ");
scanf("%d", &n);
int pages[n];
printf("Enter the reference string (pages): ");
for (i = 0; i < n; ++i) { scanf("%d", &pages[i]);
printf("Enter number of frames: ");
scanf("%d", &frames);
FIFO(pages, n, frames);
return 0; }
Output:-
LRU Algorithm
Description:- The LRU (Least Recently Used) page replacement algorithm replaces
the page that has not been used for the longest time. It tracks the usage history of
pages to ensure the least recently accessed one is removed first.
C Program:-
#include<stdio.h>
#include<stdlib.h>
int isPageInFrame(int frames[], int page, int numFrames) {
for (int i = 0; i < numFrames; i++) {
if(frames[i] == page) {return 1;} }
return 0;}
int main(){
int np,nf,faults=0,hits=0, lruIndex = 0, pages[np],frames[nf],lruOrder[nf];
printf("enter number ofpages and number offrames respectively");
scanf("%d %d",&np,&nf);
for(int i=0;i<nf;i++){
frames[i]=-1;
lruOrder[i] = -1;}
printf("enter page ids");
for(int i=0;i<np;i++){scanf("%d",&pages[i]);}
for (int i = 0; i < np; i++) {
printf("Page %d: ", pages[i]);
if(!isPageInFrame(frames, pages[i], nf)) {
for (intj = 1; j < nf; j++) {
if(lruOrder[j] < lruOrder[lruIndex]) {lruIndex =j;} }
frames[lruIndex] = pages[i];
lruOrder[lruIndex] = i;
faults++;
for (intj = 0; j < nf; j++) {
if(frames[j] != -1) { printf("%d ", frames[j]);} }
printf("(Page Fault)\n");}
else { for (intj = 0; j < nf; j++) {
if(frames[j] == pages[i]) {
lruOrder[j] = i;} }
printf("page hit\n");hits++;} }
printf("page hits=%d \n",hits);
printf("page faults=%d \n",faults);
float hitratio=(float)hits/(hits+faults);
printf("hit ratio= %.2f",hitratio);}
Output:-
LAB-10
Aim:Write a c program to simulate disk scheduling algorithms.
A)FCFS B)SCAN C)CSCAN
FCFS
Description:FCFS is a simplest disk scheduling algorithm,this algorithms allows
requests in the
order they arrive in the disk queue.
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int abs_diff(int a, int b) {return abs(a - b);}
void fcfs(int requests[], int n, int head) {
int seek_count = 0, distance, cur_track;
printf("FCFS Disk Scheduling:\n");
printf("Sequence: %d -> ", head);
for (int i = 0; i < n; i++) {
cur_track = requests[i];
distance = abs_diff(cur_track, head);
seek_count += distance;
head = cur_track;
printf("%d -> ", cur_track);}
printf("\nTotal Seek Count: %d\n", seek_count);}
int main() {
int n, head,requests[MAX];
printf("Enter the number ofrequests: ");scanf("%d", &n);
printf("Enter the requests sequence: ");
for (int i = 0; i < n; i++){scanf("%d", &requests[i]);}
printf("Enter the initial head position: ");
scanf("%d", &head);
fcfs(requests, n, head);
return 0; }
Output:-
SCAN
Description:In the SCAN Disk Scheduling Algorithm, the head starts from one end
ofthe disk and
moves towards the other end, servicing requests in between one by one and reaching
the other end. Then the direction ofthe head is reversed and the process continues as
the head
continuously scans back and forth to access the disk.
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
CSCAN
Description:The C-SCAN algorithm moves the disk head in one direction, services
requests, skips
back to the start without servicing, and resumes, treating the disk as circular for more
uniform request handling.
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int abs_diff(int a, int b) {return abs(a - b);}
void cscan(int requests[], int n, int head, int disk_size) {
int seek_count = 0, distance, cur_track;
int left[MAX], right[MAX], l_size = 0, r_size = 0;
left[l_size++] = 0;right[r_size++] = disk_size - 1;
for (int i = 0; i < n; i++) {
if(requests[i] < head) left[l_size++] = requests[i];
else right[r_size++] = requests[i];}
for (int i = 0; i < r_size; i++) {
for (intj = i + 1; j < r_size; j++) {
if(right[i] > right[j]) {
int temp = right[i];right[i] = right[j];right[j] = temp;} }
for (int i = 0; i < l_size; i++) {
for (intj = i + 1; j < l_size; j++) {
if(left[i] > left[j]) {int temp = left[i];left[i] = left[j];left[j] = temp;} } }
printf("C-SCAN Disk Scheduling:\n");printf("Sequence: %d -> ", head);
for (int i = 0; i < r_size; i++) {
cur_track = right[i];distance = abs_diff(cur_track, head);
seek_count += distance;head = cur_track;
printf("%d -> ", cur_track);}
LAB-11
LINUX COMMANDS
Aim: Study and practice of unix/linux general purpose utility command list man,
who,cat ,cd ,cp ,ps ,ls ,mv ,rm ,mkdir ,echo ,more ,date ,time ,kill ,history ,chmod ,cho
wn ,finger ,pwd ,cal ,logout ,shutdown.
1)Name : mkdir
Description: A command used to make directories.
Syntax: mkdir[option]..directory..
Options: -m,--mode=MODE :sets the file mode rwx
-p,--parent :no error f existing, make parent directory as needed.
Example: $ mkdir N200348, $ mkdir dir1
Output:
2)Name: ls
Description: list directory contents i.e lists information about files (default current
location).
Syntax: ls [option].. [file]..
Options: -a,--all=replacement of all include hidden files and directories.
-l,use a long listing format.
Example: $ ls, $ ls -a
Output:
3)Name : cd
Description: A command used to navigate between directories ,it requires either full
oath or directory name.
Syntax: cd directory
Options: None
Example: $ cd hellofile, $ cd ..
Output:
4)Name: rmdir
Description: removes directory permanently.
Syntax: rmdir [options] directory
Options: -p, removes directory and its ancestors.
--ignore-fail-on-non-empty: it ignores each failure to remove non empty
directory.
Example: rmdir outerdir, rmdir -p dir1
Output:
5)Name: touch
Description :creates an empty file or updates access and modification times of
existing files.
6)Name : cat
Description: conacatenates and displays file content.
Syntax: cat [options] file
Options: -n :number all output lines.
-b :number non blank output lines
Example: $ cat file1.txt,
$ cat >file1.txt
Add all the content and information here
Output:
7)Name : ls -l
Description: used to list files and directories and directories in long format providing
detailed information like permissions r,w,x
Syntax: ls -l file
Options: -a : include all hidden files.
-n :print sizes in human readable format.
Example: $ ls -l file.txt,
$ ls -l file.txt
Output:
8)Name: chmod
Description: changes all file permissions
Syntax: chmod [options] mode file
Options: -R : changes permission recursively
-f :suppress most error messages
Example: chmod g+w file.txt, chmod o-wx file.txt, chmod u+w file.txt
Output:
9)Name: echo
Description: displays a line of text
Syntax: exho [options] [string]
Options: -n :do not output trailing new line
-e :enable interpretation of backslash escapes
10)Name:man
Description:displays manual pages for commands
Syntax:man[options] command
Options: -k keyword :- search for keywords in manual page
-f command :- displays short description of commands
Example: $man ls
$man mkdir
Output:
11)Name:date
Description:displays or sets the system date and time
Syntax:date[options][format]
Options: -d :- --date=STRING ;displays time described by string not now
-s :- --set=STRING ;set time described by string
Example: $date
$date -d “next Monday”
$date -d “2 days ago”
Output:
12)Name:cal
Description:displays a calendar
Syntax:cal[options] [month][year]
Options: -3 :-displays previous,current&next month
-1:- displays single month
Example: $cal
$cal -3
Output:
13)Name:ps
Description: report a snapshot of current processess(process status)
Syntax: ps[options]
Options: -e :- show all processess
-f :- full format listing
Example: $ps
$ps -ef
Output:
14)Name:mv
Description:moves or renames files and directories
Syntax:mv[options] source destination
Options: -f :- do not prompt before writing
-I :-prompt before writing
Example: $mv dir1 dir2
$mv file1.txt file2.txt
Output:
15)Name: rm
Description: removes files or directories
Syntax:rm[options] file
Options: -i:- prompt before every removal
-r :- remove directories and contents recursively
Example: $rm file2.txt
$rm -r dir1
Output:
16)Name: history
Description:displays the command history
Syntax:history[options]
Options: -c :- clears the history
Example: $history
$history -c
Output:
17)Name:pwd
Description:prints the current working directory
Syntax:pwd
Options:none
Example: $pwd
Output:
18)Name: whoami
Description: prints effective user name
Syntax: whoami
Options: none
Example: $whoami
Output:
19)Name: who
Description: shows “who is logged into the system”
Syntax: who[options]
Options: -a :displays all information
-b : displays last reboot time
20)Name:time
Description:measures the time taken to execute a command also add 3 functions
named gettimeofday(),sleep()
Syntax:time
Options:None
Example: $ time ls
Output:
21)Name:kill
Description:sends a signal to kill process
Syntax:kill[options] pid
Options: -q : forcefully kills the process
-s : specifies name of number of signals to be sent
Example: $ kill 1234
$ kill -q 1234
22)Name:more
Description: views file content on screen at a time
Syntax:more[options] file
Options: -num : displays number of lines at a time
-s : squeeze multiple blank lines into one
Example: $ more file1.txt
$ more -s file1.txt
23)Name:finger
Description:displays information about system user include login name,time, etc
Syntax: finger[options][username]
Options: -l : produce a long format output
-s : produce a short format output
Example: $ finger
$ finger username
$ finger -l john
24)Name:chown
Description:changes file owner and group
Syntax: chown[options]
Options: -R : change ownership recursively
-f : supress most error messages
Example: $ chown user file1.txt
25)Name:cp
Description: copies files and directories
Syntax: cp[options] source destination
Options: -r : copy directories recursively
-I : prompt before overwrite
Example: $ cp file1.txt file2.txt
Output:
26)Name:logout
Description:logs the current user out
Syntax: logout
Options: none
Example: $ logout
27)Name: shutdown
Description: brings the system down in a safe way
Syntax: shutdown[options][time][message]
Options: -h : half the system
-r : reboot the system
Example: $ shutdown -n now
$ shutdown -r #10
LAB-12
Aim:C program that makes a copy offile using standard I/O and System calls.
Description:copying offile using standard I/O means using offopen,fclose,fwrite
functions & copying offile using system calls means using ofopen,read,write system
calls.
Using Standard I/o
#include <stdio.h>
#include <stdlib.h>
void copy_file_standard_io() {
char input_filename[256], output_filename[256];FILE *input_file,*output_file;
char buffer[1024];size_t bytes_read;
printf("Enter the source filename: ");
scanf("%255s", input_filename);
printf("Enter the destination filename: ");
scanf("%255s", output_filename);
input_file = fopen(input_filename, "rb");
if(input_file == NULL) {
perror("Error opening source file");exit(EXIT_FAILURE); }
output_file = fopen(output_filename, "wb");
if(output_file == NULL) {
perror("Error opening destination file");
fclose(input_file);
exit(EXIT_FAILURE); }
while ((bytes_read = fread(buffer, 1, sizeof(buffer), input_file)) > 0) {
fwrite(buffer, 1, bytes_read, output_file); }
fclose(input_file);
fclose(output_file);
printf("File copied successfully using standard I/O.\n");}
int main() {
copy_file_standard_io();
return 0;}
Output:-
if(sourceFile < 0) {
perror("Error opening source file");
exit(EXIT_FAILURE);}
destFile = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if(destFile < 0) {
perror("Error opening destination file");
close(sourceFile);
exit(EXIT_FAILURE);}
while ((bytesRead = read(sourceFile, buffer, sizeof(buffer))) > 0) {
bytesWritten = write(destFile, buffer, bytesRead);
if(bytesWritten != bytesRead) {
perror("Error writing to destination file");
close(sourceFile);
close(destFile);
exit(EXIT_FAILURE);} }
close(sourceFile);
close(destFile);}
int main() {
char sourceFile[256], destFile[256];
printf("Enter the source filename: ");
scanf("%255s", sourceFile);
printf("Enter the destination filename: ");
scanf("%255s",destFile);
copy_file_system_calls(sourceFile, destFile);
printf("File copied successfully usingsystem calls.\n");
return 0;}
Output:-
LAB-13
Aim:C program to emulate the UNIX ls -l command
Description:ls-l command in unix displays the details offiles in the current directory
such as file
permissions,number oflinks,owner,group,file size,and last modification time etc.,
#include <stdio.h>
#include <stdlib.h>
#include
#include
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
void print_permissions(struct stat file_stat) {
printf( (S_ISDIR(file_stat.st_mode)) ? "d" : "-");
printf( (file_stat.st_mode & S_IRUSR) ? "r" : "-");
printf( (file_stat.st_mode & S_IWUSR) ? "w" : "-");
printf( (file_stat.st_mode & S_IXUSR) ? "x" : "-");
printf( (file_stat.st_mode & S_IRGRP) ? "r" : "-");
printf( (file_stat.st_mode & S_IWGRP) ? "w" : "-");
printf( (file_stat.st_mode & S_IXGRP) ? "x" : "-");
printf( (file_stat.st_mode & S_IROTH) ? "r" : "-");
printf( (file_stat.st_mode & S_IWOTH) ? "w" : "-");
printf( (file_stat.st_mode & S_IXOTH) ? "x" : "-"); }
void print_file_info(char *filename) {
struct stat file_stat;if(stat(filename, &file_stat) < 0) { perror("stat");return; }
print_permissions(file_stat);
printf(" %ld", file_stat.st_nlink);
struct passwd *pw = getpwuid(file_stat.st_uid);
struct group *gr = getgrgid(file_stat.st_gid);
printf(" %s %s", pw->pw_name, gr->gr_name);
printf(" %ld", file_stat.st_size);
char timebuf[80];
struct tm *tm_info = localtime(&file_stat.st_mtime);
strftime(timebuf, 80, "%b %d %H:%M", tm_info);
printf(" %s", timebuf);
printf(" %s\n", filename); }
int main(int argc, char *argv[]) {
DIR *d;struct dirent *dir;d = opendir(".");
if(d == NULL) {perror("opendir");
return EXIT_FAILURE;}
while ((dir = readdir(d)) != NULL) {
if(dir->d_name[0] != '.') {
closedir(d); } } }
Output:-
LAB-14
Aim:write a c program that illustrates how to execute two commands concurrently
with a command pipe eg: ls-l|sort
Description:This C program creates two child processes to execute the commands ls -
l and sort
concurrently using a pipe. The output ofls -l is passed through the pipe and used as
the input for
sort, which sorts the list offiles and displays the sorted result on the terminal.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include
int main() {
int pipefd[2]; pid_t pid1, pid2;
if(pipe(pipefd) == -1) { perror("pipe");
exit(EXIT_FAILURE);}
pid1 = fork();// Fork the first child to run "ls -l"
if(pid1 == -1) {perror("fork");
exit(EXIT_FAILURE);}
if(pid1 == 0) {// First child process: Executes "ls -l"
close(pipefd[0]);// Close the read end ofthe pipe
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);// Close the original write end (as it's duplicated)
execlp("ls", "ls", "-l", NULL);// Execute "ls -l"
perror("execlp ls"); // If execlp fails
exit(EXIT_FAILURE);}
pid2 = fork(); // Fork the second child to run "sort"
if(pid2 == -1) { perror("fork");
exit(EXIT_FAILURE);}
if(pid2 == 0) {// Second child process: Executes "sort"
close(pipefd[1]);// Close the write end ofthe pipe
dup2(pipefd[0], STDIN_FILENO); // Redirect stdin to the read end ofthe pipe
close(pipefd[0]);// Close the original read end (as it's duplicated)
execlp("sort", "sort", NULL);// Execute "sort"
perror("execlp sort");// Ifexeclp fails
exit(EXIT_FAILURE);}
close(pipefd[0]);
close(pipefd[1]);// Parent process: Close both ends ofthe pipe
wait(NULL); // Wait for the first child finish
return 0;}
Output: