Studocu Is Not Sponsored or Endorsed by Any College or University
Studocu Is Not Sponsored or Endorsed by Any College or University
Studocu Is Not Sponsored or Endorsed by Any College or University
Practical File
LIST OF EXPERIMENTS
2. Threads
11. Disk Scheduling Algorithms: CFS, SCAN, CSCAN, LOOK, CLOOK, SSTF.
EXPERIMENT 1
AIM: To implement Process creation and termination for operating system (fork, wait,
exit, signal)
THEORY
● Fork system call creates a new process, called child process that runs parallely
with the parent process. The child process will continue execution from
after the instruction where it was forked from.
● Wait system call blocks execution of the calling process until one of its
child processes exits or a signal is received.
○ If there is at least one child process running when the call to wait() is
made, the caller will be blocked until one of its child processes exits.
At that moment, the caller resumes its execution.
○ If there is no child process running when the call to wait() is made,
then this wait() has no effect at all. That is, it is as if no wait() is there.
● Exit system call terminates the process normally. It
○ Flushes unwritten buffered data
○ Closes all open file
○ Removes temporary files
○ Returns an integer exit status to the operating system
● A signal is a software generated interrupt that is sent to a process by the
OS. Each type of signal has different code and symbolic names.
CODE
1. fork()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid = 0){
2. wait()
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t pid = fork();
if (pid = 0) {
printf("I am child process, pid = %d\n", getpid());
printf("My parent pid is %d\n", getppid());
} else {
wait(NULL);
printf("I am parent process, pid = %d\n", getpid());
printf("Because we used wait, it is guaranteed that "
"the child process has terminated\n");
}
printf("This is common to child and parent\n");
return 0;
}
3. signal()
#include<stdio.h>
#include<signal.h>
while(1){
printf("program running\n");
sleep(1);
}
return 0;
}
4. exit()
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("This program uses exit() syscall to terminate the process\n");
exit(0);
}
EXPERIMENT 2
THEORY
● Program Counter
● Register Set
● Stack Space
● Code
● Data
● Open files
● OS resources
CODE
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
if (rc) {
cout < "Error:unable to create thread," < rc < endl;
exit(-1);
}
}
pthread_exit(NULL);
EXPERIMENT 3
FCFS
First come first serve (FCFS) scheduling algorithm simply schedules the jobs
according to their arrival time. The job which comes first in the ready queue will
get the CPU first. The lesser the arrival time of the job, the sooner the job will get
the CPU.
CODE
#include<iostream>
using namespace std;
int main() {
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
cout <"Enter total number of processes(maximum 20):";
cin >n;
Shortest Job First (SJF) is an algorithm in which the process having the smallest
execution time is chosen for the next execution. In non-preemptive scheduling, once
the CPU cycle is allocated to a process, the process holds it till it reaches a
waiting state or is terminated. This scheme is also known as Shortest Job Next.
CODE
#include<stdio.h>
struct process { int id,WT,AT,BT,TAT; };
struct process a[10];
int main() {
int n,check_ar=0;
int Cmp_time=0;
float Total_WT=0,Total_TAT=0,Avg_WT,Avg_TAT;
printf("Enter the number of process \n");
scanf("%d",&n);
printf("Enter the Arrival time and Burst time of the process\n");
printf("AT BT\n");
for(int i=0;i<n;i +) {
scanf("%d%d",&a[i].AT,&a[i].BT);
a[i].id=i+1;
/ here we are checking that arrival time
/ of the process are same or different
if(i =0)
check_ar=a[i].AT;
if(check_ar =a[i].AT )
check_ar=1;
}
swap(&a[i].id,&a[j].id);
swap(&a[i].AT,&a[j].AT);
swap(&a[i].BT,&a[j].BT);
}
}
a[i].WT=Cmp_time-a[i].AT;
/ completion time of the process
Cmp_time=Cmp_time+a[i].BT;
}
}
Avg_WT=Total_WT/n;
Avg_TAT=Total_TAT/n;
for(int i=0;i<n;i +)
printf("%d\t%d\t%d\n",a[i].id,a[i].WT,a[i].TAT);
printf("Avg waiting time is: %f\n",Avg_WT);
printf("Avg turn around time is: %f\n",Avg_TAT);
return 0;
}
ROUND ROBIN
CODE
#include <stdio.h>
void main()
{
int i, NOP, sum = 0, count = 0, y, quant, wt = 0, tat = 0, at[10], bt[10],
temp[10];
float avg_wt, avg_tat;
printf(" Total number of process in the system: ");
scanf("%d", &NOP);
y = NOP;
for (i = 0; i < NOP; i +){
printf("\n Enter Arrival and Burst time of Process[%d]\n", i + 1);
printf(" Arrival time is: \t"); / Accept arrival time
scanf("%d", &at[i]);
printf(" \nBurst time is: \t"); / Accept the Burst time
scanf("%d", &bt[i]);
temp[i] = bt[i]; / store the burst time in temp array
}
count = 0;
}
if (i = NOP - 1)
i = 0;
else if (at[i + 1] = sum)
i +;
else
i = 0;
}
CODE
#include <iostream>
using namespace std;
int main() {
int a[10], b[10], x[10];
int waiting[10], turnaround[10], completion[10];
int i, j, largest, count = 0, time, n;
double avg = 0, tt = 0, end;
cout < "\nEnter the number of Processes: "; / input
cin > n;
for (i = 0; i < n; i +) {
cout < "\nEnter arrival time of process " < i + 1 < ": ";
cin > a[i];
}
for (i = 0; i < n; i +) {
cout < "\nEnter burst time of process " < i + 1 < ": ";
cin > b[i];
}
for (i = 0; i < n; i +)
x[i] = b[i];
b[9] = 0;
for (time = 0; count = n; time +){
largest = 9;
for (i = 0; i < n; i +) {
if (a[i] = time & b[i] > b[largest] & b[i] > 0)
largest = i;
}
b[largest] -;
if (b[largest] = 0){
count +;
end = time + 1;
completion[largest] = end;
waiting[largest] = end - a[largest] - x[largest];
turnaround[largest] = end - a[largest];
}
}
cout < "Process" < "\t" < "burst-time" < "\t" < "arrival-time"
< "\t" < "waiting-time" < "\t" < "turnaround-time" < "\t"
< "completion-time" < endl;
for (i = 0; i < n; i +) {
cout < "p" < i + 1 < "\t\t" < x[i] < "\t\t" < a[i]
< "\t\t" < waiting[i] < "\t\t" < turnaround[i]
< "\t\t" < completion[i] < endl;
avg = avg + waiting[i];
tt = tt + turnaround[i];
}
EXPERIMENT 4
THEORY
IPC is crucial for microkernels as the reduced core functionality in kernel needs to be
compensated by the different modules interacting with each other via IPC.
CODE
writer.cpp
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
void main() {
/ ftok function is used to generate unique key
key_t my_key = ftok("shmfile",65);
reader.cpp
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main() {
Compile commands
g + writer.cpp -o w
g + reader.cpp -o r
EXPERIMENT 5
THEORY
The critical section refers to the segment of code where processes access shared
resources, such as common variables and files, and perform write operations on
them.
CODE
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX 1e9
int i = 0;
int *limitptr = (int *)s;
int self = *limitptr;
printf("Thread %d in queue for critical section\n", self);
lock(self);
printf("Thread %d entered critical section\n", self);
for (i = 0; i < MAX; i +)
ans +;
printf("Thread %d completed executing\n", self);
printf("Thread %d is exiting critical section\n", self);
unlock(self);
}
int main() {
pthread_t p1, p2;
int a = 0, b = 1;
lock_init();
pthread_create(&p1, NULL, func, &a);
pthread_create(&p2, NULL, func, &b);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("Exiting main()\n");
return 0;
}
EXPERIMENT 6
AIM: To give solution of Producer and Consumer problem using bounded and
unbounded buffer respectively
THEORY
There is one Producer which is producing some items. And there is one Consumer
which is consuming the produced items. Producer should produce data only when
the buffer is not full. Consumer can consume data only if the memory buffer is
not empty. Also, both Producer and Consumer must not access memory at the
same time.
CODE
#include<stdio.h>
#include<stdlib.h>
int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1) {
printf("\nEnter your choice:");
scanf("%d",&n);
switch(n){
case 1: if((mutex =1) &(empty =0))
producer();
else
printf("Buffer is full !");
break;
case 2: if((mutex =1) &(full =0))
consumer();
else
printf("Buffer is empty !");
break;
case 3:
exit(0);
break;
}
}
return 0;
}
int signal(int s) {
return( +s);
}
void producer() {
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x +;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}
void consumer(){
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x -;
mutex=signal(mutex);
}
EXPERIMENT 7
THEORY
The Dining Philosopher Problem states that K philosophers are seated around a
circular table with one chopstick between each pair of philosophers. There is one
chopstick between each philosopher. A philosopher may eat if he can pick up the two
chopsticks adjacent to him. One chopstick may be picked up by any one of its
adjacent followers but not both.
CODE
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
int main() {
std :cout <"dp_5\n";
srand(time(nullptr));
std :atomic<int> m1{0}, m2{0}, m3{0}, m4{0};
t1.join();
t2.join();
t3.join();
t4.join();
}
• However if some person is reading the file, then others may read it at the same
time.
CODE
#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
sem_t x,y;
pthread_t tid;
pthread_t writerthreads[100],readerthreads[100];
int readercount = 0;
void *reader(void* param){
sem_wait(&x);
Readercount +;
if(readercount =1)
sem_wait(&y);
sem_post(&x);
printf("%d reader is inside\n",readercount);
usleep(3);
sem_wait(&x);
readercount -;
if(readercount =0){
sem_post(&y);
}
sem_post(&x);
printf("%d Reader is leaving\n",readercount+1);
return NULL;
}
int main(){
int n2,i;
printf("Enter the number of readers:");
scanf("%d",&n2);
printf("\n");
int n1[n2];
sem_init(&x,0,1);
sem_init(&y,0,1);
for(i=0;i<n2;i +) {
pthread_create(&writerthreads[i],NULL,reader,NULL);
pthread_create(&readerthreads[i],NULL,writer,NULL);
}
for(i=0;i<n2;i +) {
pthread_join(writerthreads[i],NULL);
pthread_join(readerthreads[i],NULL);
}
}
EXPERIMENT 8
THEORY
CODE
#include <iostream>
using namespace std;
int main()
{
/ P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
n = 5; / Number of processes
m = 3; / Number of resources
int alloc[5][3] = { { 0, 1, 0 }, / P0 / Allocation Matrix
{ 2, 0, 0 }, / P1
{ 3, 0, 2 }, / P2
{ 2, 1, 1 }, / P3
{ 0, 0, 2 } }; / P4
int flag = 0;
for (j = 0; j < m; j +) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}
if (flag = 0) {
ans[ind +] = i;
for (y = 0; y < m; y +)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
if(flag =1)
{
cout < "Following is the SAFE Sequence" < endl;
for (i = 0; i < n - 1; i +)
cout < " P" < ans[i] < " >";
cout < " P" < ans[n - 1] <endl;
}
return (0);
}
EXPERIMENT 9
THEORY
FIFO which is also called First In First Out is one of the types of Replacement
Algorithms. This algorithm is used in a situation where an Operating system replaces
an existing page with the help of memory by bringing a new page from the secondary
memory.
CODE
#include <stdio.h>
int main()
{
int referenceString[10], pageFaults = 0, m, n, s, pages, frames;
printf("\nEnter the number of Pages:\t");
scanf("%d", &pages);
printf("\nEnter reference string values:\n");
for( m = 0; m < pages; m +){
printf("Value No. [%d]:\t", m + 1);
scanf("%d", &referenceString[m]);
}
printf("\n What are the total number of frames:\t");
{
scanf("%d", &frames);
}
int temp[frames];
for(m = 0; m < frames; m +)
{
temp[m] = -1;
}
for(m = 0; m < pages; m +)
{
s = 0;
for(n = 0; n < frames; n +)
{
if(referenceString[m] = temp[n])
{
s +;
pageFaults -;
}
}
pageFaults +;
if((pageFaults = frames) & (s = 0))
{
temp[m] = referenceString[m];
}
else if(s = 0)
{
temp[(pageFaults - 1) % frames] = referenceString[m];
}
printf("\n");
for(n = 0; n < frames; n +)
{
printf("%d\t", temp[n]);
}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults);
return 0;
}
Least Recently Used (LRU) page replacement algorithm works on the concept that the
pages that are heavily used in previous instructions are likely to be used heavily
in next instructions. And the page that are used very less are likely to be used
less in future. Whenever a page fault occurs, the page that is least recently used is
removed from the memory frames. Page fault occurs when a referenced page is
not found in the memory frames.
CODE
#include<stdio.h>
}
printf("\n\nTotal Page Faults = %d\n", faults);
return 0;
}
Optimal page replacement algorithm says that if page fault occurs then that page
should be removed that will not be used for maximum time in future.
CODE
#include<stdio.h>
int main() {
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2,
flag3, i, j, k, pos,
max, faults = 0;
printf("Enter number of frames: ");
scanf("%d", & no_of_frames);
printf("Enter number of pages: ");
scanf("%d", & no_of_pages);
printf("Enter page reference string: ");
for (i = 0; i < no_of_pages; +i) {
scanf("%d", & pages[i]);
}
for (i = 0; i < no_of_frames; +i) {
frames[i] = -1;
}
for (i = 0; i < no_of_pages; +i) {
flag1 = flag2 = 0;
for (j = 0; j < no_of_frames; +j) {
if (frames[j] = pages[i]) {
flag1 = flag2 = 1;
break;
}
}
if (flag1 = 0) {
for (j = 0; j < no_of_frames; +j) {
if (frames[j] = -1) {
faults +;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}
if (flag2 = 0) {
flag3 = 0;
for (j = 0; j < no_of_frames; +j) {
temp[j] = -1;
for (k = i + 1; k < no_of_pages; +k) {
if (frames[j] = pages[k]) {
temp[j] = k;
break;
}
}
}
for (j = 0; j < no_of_frames; +j) {
if (temp[j] = -1) {
pos = j;
flag3 = 1;
break;
}
}
if (flag3 = 0) {
max = temp[0];
pos = 0;
for (j = 1; j < no_of_frames; +j) {
if (temp[j] > max) {
max = temp[j];
pos = j;
}
}
}
frames[pos] = pages[i];
faults +;
}
printf("\n");
for (j = 0; j < no_of_frames; +j) {
printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d\n", faults);
return 0;
}
EXPERIMENT 10
CODE
Open
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
extern int errno;
int main()
{
/ if file does not have in directory
/ then file foo.txt is created.
int fd = open("foo.txt", O_RDONLY | O_CREAT);
printf("fd = %d\n", fd);
if (fd =-1)
{
/ print which type of error have in a code
printf("Error Number % d\n", errno);
/ print program detail "Success or failure"
perror("Program");
}}
System Calls
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
close(fd);
}
void read_student() {
Student student;
int fd = open(file_path, O_RDONLY);
if (fd < 0) {
printf("\nError reading file");
exit(0);
} else {
while (read(fd, & student, sizeof(student)))
printf("Name: %s\nRoll Number: %d\nPercentage: %f\n", student.name,
student.roll,
student.percentage);
}
close(fd);
}
void delete_student(int rno) {
char * tmp = "temp";
Student student;
int fd1 = open(file_path, O_RDONLY);
int fd2 = open(tmp, O_CREAT | O_WRONLY);
if (fd1 < 0) {
printf("\nError reading file");
exit(0);
} else {
while (read(fd1, & student, sizeof(student))) {
if (student.roll = rno) {} else {
write(fd2, & student, sizeof(student));
}
}
}
remove(file_path);
rename(tmp, file_path);
close(fd1);
close(fd2);
}
void search_student(int rno) {
Student student;
int fd1 = open(file_path, O_RDONLY);
int flag = 0;
if (fd1 < 0) {
printf("\nError reading file");
exit(0);
} else {
while (read(fd1, & student, sizeof(student))) {
if (student.roll = rno) {
printf("Name: %s\nRoll Number: %d\nPercentage: %f\n", student.name,
student.roll,
student.percentage);
flag = 1;
}
}
}
if (flag = 0)
printf("\nRecord not Found!");
close(fd1);
}
int main(int argc, char
const * argv[]) {
Student student;
int ch;
int fd, r;
char dname[20];
while (1) {
printf("\n1. Create database \n2. Insert Record \n3. Read Record \n4.
Delete Record \n5. Search Record \n6. Exit \n >");
scanf("%d", & ch);
switch (ch) {
case 1: {
printf("Enter database name: ");
scanf("%s", dname);
file_path = dname;
int fd = open(file_path, O_CREAT);
if (fd < 0) {
printf("\nError creating file");
exit(0);
} else {
printf("\nFile created successfully!\n");
}
close(fd);
}
break;
case 2: {
printf("\nEnter the Roll Number, Name and Percentage\n"); scanf("%d
%s%f", & student.roll, student.name, & student.percentage);
write_student(student);
}
break;
case 3: {
read_student();
}
break;
case 4: {
printf("\nEnter roll no:");
scanf("%d", & r);
delete_student(r);
}
break;
case 5: {
printf("\nEnter roll no:");
scanf("%d", & r);
search_student(r);
}
break;
case 6:
exit(0);
default:
printf("\nInvalid Choice!");
}
}
return 0;
}
EXPERIMENT 11
AIM: To implement the various disk scheduling algorithms
THEORY
CODE
CODE
seek_count += distance;
/ accessed track is now new head
head = cur_track;
}
direction = "left";
}
}
cout < "Total number of seek operations = "
< seek_count < endl;
cout < "Seek Sequence is" < endl;
for (int i = 0; i < seek_sequence.size(); i +) {
cout < seek_sequence[i] < endl;
}
}
/ Driver code
int main()
{
/ request array
int arr[sz] = { 176, 79, 34, 60,
92, 11, 41, 114 };
int head = 50;
string direction = "left";
SCAN(arr, head, direction);
return 0; }
Elevator Algorithm” as it essentially treats the cylinders as a circular list that wraps
around from the final cylinder to the first one.
CODE
#include <bits/stdc +.h>
cur_track = left[i];
/ appending current track to seek sequence
seek_sequence.push_back(cur_track);
/ calculate absolute distance
distance = abs(cur_track - head);
/ increase the total count
seek_count += distance;
/ accessed track is now the new head
head = cur_track;
}
cout < "Total number of seek operations = " <
seek_count < endl;
cout < "Seek Sequence is" < endl;
for (int i = 0; i < seek_sequence.size(); i +) {
cout < seek_sequence[i] < endl;
}
}
/ Driver code
int main() { / request array
int arr[sz] = {
176,
79,
34,
60,
92,
11,
41,
114
};
int head = 50;
cout < "Initial position of head: " < head < endl;
CSCAN(arr, head);
return 0;
}
CODE
#include <bits/stdc +.h>
CODE
cur_track = right[i];
seek_sequence.push_back(cur_track);
distance = abs(cur_track - head);
seek_count += distance;
head = cur_track;
}
seek_count += abs(head - left[0]);
head = left[0];
for (int i = 0; i < left.size(); i +) {
cur_track = left[i];
seek_sequence.push_back(cur_track);
distance = abs(cur_track - head);
/ Increase the total count
seek_count += distance;
/ Accessed track is now the new head
head = cur_track;
}
cout < "Total number of seek operations = " <
seek_count < endl;
cout < "Seek Sequence is" < endl;
for (int i = 0; i < seek_sequence.size(); i +) {
cout < seek_sequence[i] < endl;
}
}
int main() {
/ Request array
int arr[sz] = {
176,
79,
34,
60,
92,
11,
41,
114
};
int head = 50;
cout < "Initial position of head: " < head < endl;
CLOOK(arr, head);
return 0;
}
CODE
60,
92,
11,
41,
114
};
int head = 50;
FCFS(arr, head);
return 0;
}