1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
echo "Enter a number"
read number
if((number %2==0)); then
echo "The $number is even"else
echo "The number $number is odd"
fi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
echo "Enter a year"
read year
if((year%400==0)); then
echo "$year is a leap year"elif((year%100==0)); then
echo "$year is a leap year"elif((year%4==0)); then
echo "$year is a leap year"else
echo "$year is not a leap year"
fi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!bin/bash
echo "Enter a number"
read num
factorial=1if((num<0)); then
echo "Error: Factorial is not defined for negative numbers"elif((num ==0)); then
echo "Factorial of 0 is 1"elsefor((i=1;i<=num;i++));do
factorial=$((factorial*i))
done
echo "Factorial of $num is $factorial"
fi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<sys/types.h>#include<sys/wait.h>#include<sys/stat.h>#include<dirent.h>intmain(){
pid_t child_pid;int status;
child_pid =fork();// Create a child process by forking the current processif(child_pid ==-1){// If the fork failed, print an error message and exitperror("Fork failed");exit(EXIT_FAILURE);}elseif(child_pid ==0){// Child processchar*args[]={"ls","-l",NULL};// Arguments for the "ls" commandexecvp("ls",args);// Execute the "ls" command with the given argumentsperror("Exec failed");// execvp only returns if an error occurs, so print an error message and exitexit(EXIT_FAILURE);}else{// Parent processprintf("Parent process: PID = %d, Child PID = %d \n",getpid(),child_pid);// Print the process IDs of the parent and child processeswait(&status);// Wait for the child process to exit and store its statusif(WIFEXITED(status)){// Check if the child process exited normallyprintf("Child process exited with status %d\n",WEXITSTATUS(status));// Print the exit status of the child process}}int fd =close(STDOUT_FILENO);// Close the standard output file descriptorif(fd ==-1){// If closing the file descriptor failed, print an error message and exitperror("Close failed");exit(EXIT_FAILURE);}structstat st;if(stat("example.txt",&st)==0){// Check if "example.txt" file exists// File exists
DIR *dirp;
dirp =opendir(".");// Open the current directorystructdirent*dptr;while((dptr =readdir(dirp))!=NULL){// Read directory entries one by oneprintf("%s\n",dptr->d_name);// Print the name of each entry}}return0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<fcntl.h>intmain(){int fd, numBytes;char buffer[100];// Open file in read only mode
fd = open ("input.txt",O_RDONLY);if(fd==-1){perror("Failed to open the file");exit(EXIT_FAILURE);}//Read data from the file
numBytes =read(fd,buffer,sizeof(buffer));if(numBytes ==-1){perror("Failed to read from the file");exit(EXIT_FAILURE);}// Write the read data to the consoleif(write(STDOUT_FILENO,buffer,numBytes)==-1){perror("Failed to write to console");exit(EXIT_FAILURE);}// Close the fileif(close(fd)==-1){perror("Failed to close the file");exit(EXIT_FAILURE);}return0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
The formulas to know are
Turn Around Time = Completion Time - Arrival Time
Waiting Time = Turnaround time - Burst Time
TAT = CT - AT
WT = TAT - BT
- First we need to start
- Then inside the structure we need to declare some variables
- So, since we need processes, first we ask how many processes is needed,and the value is stored in n
- After entering the number of processes, we enter the details of the each process, the loop count is the number of processes we entered earlier
- The details are
- Process id
- Arrival time
- Burst time
- After that we sort the procesess based on the arrival time
- Now visualize a table, with all our values,- AT BT CT TAT WT
- What values are missing?- CT TAT and WT
- So we can calculate them one by one
- First we will calculate CT
- For calculating CT, we will be iterating over the processes one by one
- CT value of i will be equal to CT value of the previous process + Burst Time of current process
- Next we will be calculating the turnaround time and waiting time
- We use the formulas for each and calculate and assign to that process
- Along side also calculate the total waiting time and turnaround time, so we can calculate the averages later.- Calculate the Avg TAT and WT,and display it
- FCFS CPU scheduling is now done!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
First we need to start
- Then inside the structure we need to declare some variables
- So, since we need processes, first we ask how many processes is needed,and the value is stored in n
- After entering the number of processes, we enter the details of the each process, the loop count is the number of processes we entered earlier
- The details are
- Process id
- Arrival time
- Burst time
- After that we sort the procesess based on the arrival time
- Now we need to schedule the processes
- We go through the processes one by one
- We update the btime variable, by adding the the burst time of the current process
- We set a miniumum burst time variable variable as the burst time in the kth process
- the kth process is what we initialtize as the process with the minimum burst time
- Now since we have all these variables we will be comparing the minimum burst time with the current burst time and it gets updated if the current process burst time is less than the specified burst time
- The swapping is done if it satisfies the following conditions
- the arrival time is reached
- the burst time is less than the minimum
- The swapping will swap out the process id, at and bt
- At the end we update the k variable by one
- Now since the scheduling is done
- We will be calculating the remaining values like CT, TAT, WT
- First we will calculate CT
- For calculating CT, we will be iterating over the processes one by one
- CT value of i will be equal to CT value of the previous process + Burst Time of current process
- Next we will be calculating the turnaround time and waiting time
- We use the formulas for each and calculate and assign to that process
- Along side also calculate the total waiting time and turnaround time, so we can calculate the averages later.- Calculate the Avg TAT and WT,and display it
- SJF CPU scheduling is now done!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<stdio.h>intmain(){int burst_time[20], process[20], waiting_time[20], turnaround_time[20],priority[20];int i,j, limit, sum =0, position, temp;float avg_wait_time, avg_turnaround_time;// Input the number of processesprintf("Enter the number of processes");scanf("%d",&limit);// Input burst time and priority for each processprintf("Enter burst time and priority for %d processes\n",limit);for(i=0; i<limit;i++){printf("\n Process [%d]\n",i+1);printf("Process burst time");scanf("%d",&burst_time[i]);printf("Process priority");scanf("%d",&priority[i]);
process[i]= i+1;}// Sort the processes based on priority using bubble sortfor(i =0; i < limit -1; i++){for(j =0; j < limit - i -1; j++){if(priority[j]> priority[j +1]){// Swap if current element has higher priority// Swap priority
temp = priority[j];
priority[j]= priority[j +1];
priority[j +1]= temp;// Swap burst time
temp = burst_time[j];
burst_time[j]= burst_time[j +1];
burst_time[j +1]= temp;// Swap process ID
temp = process[j];
process[j]= process[j +1];
process[j +1]= temp;}}}// Calculate waiting time for each process
waiting_time[0]=0;for(i=1;i<limit;i++){
waiting_time[i]=0;for(j=0;j<i;j++){
waiting_time[i]+= burst_time[j];}
sum+= waiting_time[i];}// Calculate average waiting time
avg_wait_time =(float)sum/limit;
sum=0;// Print the process ID, burst time, waiting time, and turnaround time for each processprintf("Process ID\t Burst time\t Waiting Time\t Turnaround Time\n");for(i=0;i<limit;i++){
turnaround_time[i]= burst_time[i]+ waiting_time[i];
sum+=turnaround_time[i];printf("Process[%d]\t%d\t%d\t%d\n",process[i],burst_time[i],waiting_time[i],turnaround_time[i]);}// Calculate average turnaround time
avg_turnaround_time =(float)sum/limit;// Print the average waiting time and average turnaround timeprintf("Average waiting time %2f\n",avg_wait_time);printf("Average Turnaround Time %2f \n",avg_turnaround_time);return0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
WT = TAT - BT
TAT = WT + BT
turnaround_time[i]= burst_time[i]+ waiting_time[i];
First we need to start
- Then inside the structure we need to declare some variables
- So, since we need processes, first we ask how many processes is needed,and the value is stored in n
- After entering the number of processes, we enter the details of the each process, the loop count is the number of processes we entered earlier
- The details are
- Burst time
- Priority
- Next we will be sorting the processes based on priority
- first we will setting the position to the ith position
- We assume that this position has the minimum priority
- In the inner loop, each priority[j] is compared with priority[position] to find the index (position) of the process with the highest priority. If a process with higher priority is found, the 'position' variable is updated.- After the inner loop finishes, the process with the highest priority among the remaining processes (starting from i) is found. The 'position' variable contains the index of that process.- The values of priority[i], burst_time[i],and process[i] are swapped with the process of higher priority
- After executing this code, the 'priority','burst_time',and'process' arrays will be sorted in ascending order based on the priority of the processes.- Now we calculate the remaining
- Waiting time
- For waiting time we add waitingtime + burst time for each process
- We also add the waiting time sum to calculate the average waiting time later
- Then we calculate turnaround time
- We use the formula TAT = WT + BT
- Also add the sum for average calculation later
-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
- First we need to start
- Then inside the structure we need to declare some variables
- So, since we need processes, first we ask how many processes is needed,and the value is stored in n
- Assign a variable procnum to the number of processes,this will be used later in the program
- After entering the number of processes, we enter the details of the each process, the loop count is the number of processes we entered earlier
- The details are
- Arrival time
- Burst time
We will also be assigning remainingtime[i] to the burst time,for calculating the remaining time
- Since its a round robin program, we will input the time quantum
- After that we will be starting a loop which goes over each processes until all processes are complete
- The loop will run until all the processes have been executed
- There will be a series of conditions we will be checking
- Condition 1.1: If the process remaining burst time can finish within the time quantum
- If the condition is true- the total execution time (`total`) is increased by `temp[i]`
- `temp[i]` is set to 0 to indicate that the process has completed(Burst time is completely exausted).- The `counter` variable is set to 1 to mark that a process has finished.- Condition 1.2 Process does not complete within the time quantum and remaining burst greater than 0- If this is true, the quantum amount will be consumed from the process, leaving behind burst - quantum left
- And the total is updated with the quantum, since that much amount is consumed
- Condition 2.1 This will check if the process is completed
- Procnum will be decremented
- The relevant info will be printed
- Condition 31. The next `if` statement checks if `i` has reached the last process.- If true, it means that the current process is the last process in the list. In thiscase, `i` is set to 0 to start processing from the beginning.2. The last `else` statement handles the case when the next process arrival time is less than or equal to the current total execution time (`total`).- If true, it means that the next process has arrived and should be processed. `i` is incremented to move to the next process.3. If none of the above conditions are satisfied, it means that no process is available for processing at the moment.- In thiscase, `i` is set to 0 to start processing from the beginning.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
**isPageFault(frames, size, page)**- Here we iterate through the pages,if any one of the frame values equals the given page, then theres no page fault
- Else theres a page fault
**printFrames(frames, size)**
We iterate through the frames,and we will print them, leave a hyphen if the frame value is -1- First we define the set of pages
- Then we also store the number of pages
- Then we execute the function
- fifopagereplacement, which takes pages and number of pages
- Here first we initialize an array, called frame,and it has the size defined(SIZE = framesize)- Since the entire array doesnt have any values, we will fill it up with -1s
- Now since we have got the array ready,- We will iterate over the pages mentioned in the function
- We execute a function called isPageFault, which checks whether its a page fault
- If its a page fault
- We will place thisnew page into the frame
- The position in the frame is determined by front variable
- After assigning, we will update this front variable by front =(front+1)%FRAME_SIZE
- And we also increment the pagefaults variable to keep a count of that
- Once thats done we execute a function called printframes(frames, FRAME_SIZE) which prints out the new frame
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include<stdio.h>#define FRAME_SIZE 3// Function to print the framesvoidprintFrames(int frames[],int size){for(int i=0;i<size;i++){if(frames[i]==-1){printf("-");}else{printf("%d",frames[i]);}}printf("\n");}// Function to check if a page is a page faultintisPageFault(int frames[],int size,int page){for(int i=0;i<size;i++){if(frames[i]== page){return0;// Page found in the frames, no page fault}}return1;// Page not found in the frames, page fault}// Function to get the least recently used page from the framesintgetLRUPage(int frames[],int pageIndices[],int size){//finds the frame with the minimum page index in the pageIndices array//and returns the corresponding page value from the frames array.(This is the LRU PAGE) int lruIndex =0;for(int i=1;i<size;i++){if(pageIndices[i]< pageIndices[lruIndex]){
lruIndex = i;// Update the index of the least recently used page}}return frames[lruIndex];// Return the value of the least recently used page}// Function to update the page indices after a page is accessed// Example, Suppose we access the page index 1// Before: pageIndices: [2, 3, 1]// After: pageIndices: [3, 0, 2]// 0 Signifies the page index 1 is the most recently usedvoidupdatePageIndices(int pageIndices[],int size,int pageIndex){for(int i=0;i<size;i++){if(pageIndices[i]!=-1){// Checks if its an empty frame which has page index of -1
pageIndices[i]++;// Increment the page index if it is not -1, This signifies the page has been updated recently}}
pageIndices[pageIndex]=0;// Set the page index of the recently accessed page to 0}// Function to perform LRU page replacementvoidlruPageReplacement(int pages[],int numPages){int frames[FRAME_SIZE];// Array to store the framesint pageIndices[FRAME_SIZE];// Array to store the page indicesint pageFaults =0;// Counter for page faults// Initialize frames and page indices with -1for(int i=0;i<FRAME_SIZE;i++){
frames[i]=-1;
pageIndices[i]=-1;}printf("Page Faults\n");for(int i=0; i<numPages;i++){printf("Page %d:", pages[i]);if(isPageFault(frames, FRAME_SIZE, pages[i])){// Check if current page is a page faultint lruPage =getLRUPage(frames, pageIndices, FRAME_SIZE);// If its a page fault, least recently used page is searchedint pageIndex =-1;// Find the index of the least recently used page in the framesfor(int j=0; j<FRAME_SIZE; j++){if(frames[j]== lruPage){
pageIndex = j;// Store the index of the least recently used pagebreak;}}
frames[pageIndex]= pages[i];// Replace the least recently used page with the current pageupdatePageIndices(pageIndices, FRAME_SIZE, pageIndex);// Update the page indices
pageFaults++;// Increment the page fault countprintFrames(frames, FRAME_SIZE);// Print the current state of the frames}else{updatePageIndices(pageIndices, FRAME_SIZE, i);// Update the page indicesprintf("No page fault occurred\n");}}printf("Total page faults: %d\n", pageFaults);}intmain(){int pages[]={1,2,3,4,5,3,1,6,7,8,7,8,9,3,9,5};int numPages =sizeof(pages)/sizeof(pages[0]);lruPageReplacement(pages, numPages);return0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
### LRU PAGE REPLACEMENT
**isPageFault(frames, size, page)**- Here we iterate through the frames,if any one of the frame values equals the given page, then theres no page fault
- Else theres a page fault
**getLRUPage(int frames[],int pageIndices[],int size)**- We set a variable named lruindex to 0- Then we go through each element of page indices
- We start from index 1 since lruindex is already set to 0- Inside the loop we check if the page index of the current element is less that the lruindex
- This indicates that the current index is less recently used, hence we update the lruindex to this value
- By the end of the loop we will obtain the LRU index
- Now we return the value corresponding to the LRU index value, which is the least recently used frame
First we define the set of pages
- Then we also store the number of pages
- Then we execute the function
- lrupagereplacement,this takes the pages and amount of pages
- First we declare the frames using an array
- Then we also declare page index array
- We fill both these arrays with -1s
- Then we iterate through the pages
-**if page fault occurred (using function isPageFault)**- We will obtain the least recently used page usingfunction(**getLRUPage**) where we provide the frames, indices,and frame size
- We initialize pageIndex as -1- We iterate through the frame to find the index of the LRU
-if it matches we update the pageindex with the value
- After getting the page index
- We will put thisnew page number into the page index position in the frame
- Then we will be updating the page indices after thisnew change by providing the page index
- Increment the page fault count
- Print the frames
- If no page fault occured
- update the page indices, with the ith position
- Print out the total page faults
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<stdio.h>#include<limits.h>#define FRAME_SIZE 3// Function to print the contents of the framesvoidprintFrames(int frames[],int size){for(int i =0; i < size; i++){if(frames[i]==-1){printf("- ");}else{printf("%d ", frames[i]);}}printf("\n");}// Function to check if a page fault occurredintisPageFault(int frames[],int size,int page){for(int i =0; i < size; i++){if(frames[i]== page){return0;// Page found in frames, no page fault}}return1;// Page not found in frames, page fault occurred}// Function to get the least frequently used page from the frames// Example// Frames: [1, 2, 3]// Counts: [2, 3, 1]// 1 is the least count here, so the LFU is its corresponding frame which is 3intgetLFUPage(int frames[],int counts[],int size){int lfuIndex =0;// Setting least frequently used index to 0int minCount = INT_MAX;// Setting the minimum count found so far to the for(int i =0; i < size; i++){if(counts[i]< minCount){
minCount = counts[i];// Sets the least count
lfuIndex = i;}}return frames[lfuIndex];// Return the least frequently used page}// Function to update the count of a page in the framesvoidupdatePageCount(int pages[],int counts[],int size,int page){for(int i =0; i < size; i++){if(pages[i]== page){
counts[i]++;// Increment the count for the pagebreak;}}}// Function to perform LFU page replacementvoidlfuPageReplacement(int pages[],int numPages){int frames[FRAME_SIZE];// Frames to hold the pagesint counts[FRAME_SIZE];// Count of each page in the framesint pageFaults =0;// Counter for page faults// Initialize frames and counts with default valuesfor(int i =0; i < FRAME_SIZE; i++){
frames[i]=-1;// -1 represents an empty frame
counts[i]=0;// Initialize count to 0 for each frame}printf("Page Faults: \n");for(int i =0; i < numPages; i++){printf("Page %d: ", pages[i]);if(isPageFault(frames, FRAME_SIZE, pages[i])){int lfuPage =getLFUPage(frames, counts, FRAME_SIZE);// Find the least frequently used pageint pageIndex =-1;// Find the index of the least frequently used page in framesfor(int j =0; j < FRAME_SIZE; j++){if(frames[j]== lfuPage){
pageIndex = j;break;}}
frames[pageIndex]= pages[i];// Replace the least frequently used page with the new page
counts[pageIndex]=1;// Reset the count for the new page
pageFaults++;// Increment the page fault countprintFrames(frames, FRAME_SIZE);// Print the updated frames}else{updatePageCount(frames, counts, FRAME_SIZE, pages[i]);// Update the count for the existing pageprintf("No page fault occurred.\n");}}printf("\nTotal Page Faults: %d\n", pageFaults);}intmain(){int pages[]={1,2,3,4,5,3,1,6,7,8,7,8,9,3,9,5};int numPages =sizeof(pages)/sizeof(pages[0]);lfuPageReplacement(pages, numPages);// Perform LFU page replacementreturn0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
### LFU PAGE REPLACEMENT
**printFrames()**
Iterate through each frame and print value,if its -1 then put as hyphen
**isPageFault(frames. page)**
Iterate through each frame, check page = frame, then no page fault
**getLFUPage**- We set the lfuindex as 0-and mincount to highest value possible
- We iterate through count and compare with mincount
-and set the mincount accordingly if count < mincount
- also update the lfuindex
- By the end of the loop we get the lfuindex
- We will return the value of frame at lfuindex
**updatePageCount()**- We iterate through the pages,if the pages are matching, we update the count by 1andbreak
First we define the set of pages
- Then we also store the number of pages
- Then we execute the function
- lfupagereplacement,this takes the pages and amount of pages
- First we will declare the frames
- Then we have another array called count, which has a count for each page in the frame
- We set all the frame values to -1- We also set all the count values to 0- Now we will iterate over the pages
- If its a page fault
- We will get the LFU value
- We will set the page index to -1- We iterate through each frame
- If the frame equals the LFU
- the page index is noted
- page index location value is then replaced with the new value
- the count value is reset to 1- page faults are incremented
- The frames are printed
- If its not a page fault
- We update the page count
- Print total page faults
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
### checksafestate()- First we will check if execution count!= number of processes
- We initialize is_safe variable to 0- Then we iterate through the process
-if process.is_executing
- we set canexecute =1- Now we check if the remaining need is greater than avaiable
- If so, then we set canexecute to 0andbreak- After iterating then we check the process is able to execute ornot-if its able to execute
- We increment the avaialable resources with the allocated resources
- And we set the process is_executing to 0- Its set to safe state
- Execution sequence is appended with the new process id
- update the execution count
- If system is not safe, then print the corresponding message
- If its safe, print out the sequence
### requestResource()- First we request the process id where the request for resource is done
- Then we iterate over the number of resources
- We enter the new resource amount
- It checks if the new resource amount is less than or equal to the remaining need of the process
-if that's true- it will check if the new resource amount is less than or equal to the available resource, since we need to check if its compatible
- Now we will consume the new_resources amount from available resources
- Since this is consumed, the allocated value of the process is incremented with the new resources
- Since some of the need is satisfied, we will be subtracting the new resource from the need
-else- waiting is set to 1-ifnottrue- It means the new resource amount is greater than remaining need
- So max_usage_exceeded is set to 1- If we max usage is not exceeded and the process is not waiting, then we need to determine the safe state
The equation used need = MAX - Allocation
- First we enter the number of processes for bankers algorithm
- Then we enter the number of resource types like (A B C D)- Then we enter the data for the available resoures
- After that we will enter the resource details
- First we enter allocation matrix
- Then we enter max resource request
- Then we set the process as is_executing
- After entering the resource details we will be calculating the need of each process
- We know that need = MAX - Allocation
- After that we will print the whole table with pid, allocation, max and need
- After printing we will check the safestate
- After checking that we will have a prompt to check for resource request
- The user can Request new resources by entering process id
- it will execute requestResources()-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
- First we have the requests
- Then we calculate the number of requests
- We set the head as a number
- We execute function fcfsdiskscheduling
- We set the totalseektime as 0- Then we set the current to head
- We print out the head as it starts there
- We iterate through each request,- We calculate the distance by finding the difference between current and the current request
- Then we add this difference to the total seek time
- Then we update and print the current variable
- After that we print the total seek time
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<stdio.h>#include<stdlib.h>intmain(){int ioq[20], i, n, j, ihead, temp, scan, tot;float seek =0, avgs;// Prompt user for the number of requestsprintf("Enter the number of requests: ");scanf("%d",&n);// Prompt user for the initial head positionprintf("Enter the initial head position: ");scanf("%d",&ihead);
ioq[0]= ihead;
ioq[1]=0;
n +=2;// Prompt user for I/O queue requestsprintf("Enter the I/O queue requests:\n");for(i =2; i < n; i++){scanf("%d",&ioq[i]);}// Sort the I/O queue requestsfor(i =0; i < n -1; i++){for(j =0; j < n - i -1; j++){if(ioq[j]> ioq[j +1]){
temp = ioq[j];
ioq[j]= ioq[j +1];
ioq[j +1]= temp;}}}
ioq[n]= ioq[n -1];// Find the initial head position in the sorted I/O queuefor(i =0; i < n; i++){if(ihead == ioq[i]){
scan = i;break;}}printf("\nOrder of request served:\n\n");
tot =0;// Serve requests in the lower directionfor(i = scan; i >=0; i--){if(i ==0)// For last element we will calculate the distance from 0 to scan +1
tot =abs(ioq[i]- ioq[scan +1]);else
tot =abs(ioq[i]- ioq[i -1]);// if (tot < 0)// tot = -tot;printf("%d\t%d\n", ioq[i], tot);}// Serve requests in the upper directionfor(i = scan +1; i < n; i++){
tot =abs(ioq[i +1]- ioq[i]);// if (tot < 0)// tot = -tot;printf("%d\t%d\n", ioq[i], tot);}// Calculate seek time and average seek time
seek = ihead + ioq[n -1];
avgs = seek /(n -2);printf("\n\nTotal seek time: %.2f\n", seek);printf("Average seek time: %.2f\n\n", avgs);return0;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Moves in a single direction (either towards the innermost or outermost track)and services requests in that direction
- First we calculate the amount of requests we need
- Then we ask for the intitial head position
- We declare a variable called ioq,for the queue of this schedule
- The first element is the head,2nd is 0, since its a scan schedule, we go to the very left
- Then we enter the i/o requests one by one upto the specified number of request
- After that we sort out the queue requests in ascending order
- Then we find the head position among the sorted queue
- And set that to the scan variable
- The first `for` loop serves the requests in the lower direction of the queue. It iterates from `scan` down to 0(inclusive). The variable `i` represents the current index being processed.- The second `for` loop serves the requests in the upper direction of the queue. It starts from `scan +1` and iterates up to `n -1`
- Then we calculate seek = ihead + ioq[n-1]- avgs = seek/(n-2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<stdio.h>voidmain(){int ioq[20], i, n, j, ihead, itail, temp, scan, tot =0;float seek =0, avgs;// Prompt user for the number of requestsprintf("Enter the number of requests: ");scanf("%d",&n);
ioq[0]=0;// Prompt user for the initial head positionprintf("Enter the initial head position: ");scanf("%d",&ihead);
ioq[1]= ihead;// Prompt user for the maximum track limitprintf("Enter the maximum track limit: ");scanf("%d",&itail);
ioq[2]= itail;
n +=3;// Prompt user for I/O queue requestsprintf("Enter the I/O queue requests:\n");for(i =3; i < n; i++){scanf("%d",&ioq[i]);}// Sort the I/O queue requestsfor(i =0; i < n -1; i++){for(j =0; j < n -1; j++){if(ioq[j]> ioq[j +1]){
temp = ioq[j];
ioq[j]= ioq[j +1];
ioq[j +1]= temp;}}}// Find the initial head position in the sorted I/O queuefor(i =0; i < n; i++){if(ihead == ioq[i]){
scan = i;break;}}
i = scan;
temp = n;printf("\nOrder of requests served:\n\n");printf("\n");while(i != temp){if(i < temp -1){
tot =abs(ioq[i +1]- ioq[i]);
seek += tot;}printf("%d-->", ioq[i]);
i++;if(i == n)// Checks if the end is reached, is so, then the seek goes to the beginning{
i =0;
temp = scan;
seek += itail;// The distance between start and end is added since, it goes back}}
avgs = seek /(n -3);printf("\n\nTotal seek time: %.2f", seek);printf("\nAverage seek time: %.2f\n\n", avgs);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Moves in a single direction, but when it reaches the end of the disk, it quickly jumps to the other end without servicing any requests in between.- First we enter the number of requests
- And we set the first element of the queue as 0- We enter the initial head position
- And put it as the ioq[1] position
- Then we enter the track limit
- We put this track limit as the 3rd element in the queu
- Then we enter the actual i/o requests
- Then we sort these requests
- Then we find the position of head
- Then we do a while loop, setting i as scan
- We calculate the distance between i and i+1- And add this distance to total seek
- A check is made if i is in the end
- If it reaches end, then the i position is set to 0- And the upper limit temp is set to scan
- Seek time is incremented with the value of the tracking limit
- Average is calculated at the end dividing by the number of requests -3- Total seek and average seek time is displayed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
- First we have a set of options
- Producer, consumer, exit
- If producer is chosen
- A check for mutex condition and whether empty spaces are !=0 is taken
- Insider producer() function
- First we decrement the mutex value to make it unavailable and aquire the lock
- This is done usingwait() signal
- After that, since production is being done, we will increment the full variable
- This is done usingsignal() semaphore
- Since production consumes empty space we will decrement empty
- This is done by using the wait() signal
- Now we actually do the production by incrementing x variable
- Since the operation is complete, we will now disable the mutex lock by incrementing the mutex value to 1- If the check fails, then we know that either the lock is aquired or the memory is being completely used
- We will print that, the buffer is full
- If consumer is chosen
- We will check for mutex lock(mutex ==1)and full variable is not equal to 0(To ensure that there will be something to consume)- Inside consumer() function
- First we aquire the mutex lock by doing wait() on mutex to make it 0- Then, since the full value is being consumed, we will be decrementing the full variable, so we will be doing a wait() operation
- Since the amount of empty space will increase since consumption is happening, we will be doing signal() function to decrement the operation
- We will now consume by decrementing x variable
- Now we remove the mutex lock by doing signal() operation and making the mutex value 1- Else
- We have to display that the buffer is empty
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- First we iterate 10 times
- We intialize the flags to 0- We intialize the allocation to -1- Then we enter the number of blocks that we need
- After that we enter the size of each block
- We iterate bno number of times and read bsize for each block
- Then we enter the number of processes
- Then we enter the size of each processes
- Then we do a set of for loops
- First we iterate through the processes
- Then we iterate through each block of the process
- If the block size is greater than or equal to process size
- We will allocate j block to ith process
- Since this block is allocated, now we minus the process size from the block size
- Then we print out the Process number , size,and block no
- Print only if the allocation is not-1- Print the number, allocation[i]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- First we enter the number of blocks
- Then we enter the number of processes
- Then we iterate through the blocks to enter the size of each block
- Then we enter the size of each processes
- We declare allocatedblocks array as an array of 0s to mark allocation of block
- Then we start a series of for loops
- First we iterate through the processes
- Then we iterate through the blocks of each process
- If the block is unnoccupied (barray is 0)- Remaining space in the block is calculated
- It checks if the difference is greater than 0andif the difference is less than the least value
- This check will ensure the difference is the minimum which ensures best fit
- After evaluating all blocks for the current process, the program marks the block that has been selected as the best fit as "allocated" by setting the corresponding index in the `allocatedBlocks` array to 1.- Print the process number, process size, block no, block size
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- Enter the number of blocks
- Enter size of each blocks
- Enter the number of processes
- Enter size of each processes
- Also assign block allocation to -1 indicate that the block is not being allocated
- Then we iterate through each process
- We set the index of the worst block as -1- We iterate through each block in a process
- We do a check if the given process is greater than or equal to the process size
- If its true, then we will check if the worst block index is -1-if its true, then the current block will become the worst block
- Else we compare the worst block to the current block
-if the current block is larger, it will be set as the worst block
- We get the worst block in the end
- the worst block will be allocated to allocation matrix
- Block size of the worst index will be minused with the process size
- We will print process number, process size, Block number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<sys/types.h>// for key_t#include<sys/ipc.h>// For IPC#include<sys/shm.h>//Creating attaching shared memory#include<stdio.h>#include<stdlib.h>// Exit and memory allocation functions#include<unistd.h>// Include this header for the sleep function#define SHMSZ 27intmain(){char c;int shmid;
key_t key;char*shm,*s;
key =5678;// Key used to identify the shared memory segment// Create a new shared memory segment or attach to an existing oneif((shmid =shmget(key, SHMSZ, IPC_CREAT |0666))<0){// 0666 permission modeperror("shmget");exit(1);}// Attach the shared memory segment to the process's address spaceif((shm =shmat(shmid,NULL,0))==(char*)-1){perror("shmat");exit(1);}
s = shm;// Set 's' pointer to point to the beginning of the shared memory// Write the letters from 'a' to 'z' into the shared memory segmentfor(c ='a'; c <='z'; c++)*s++= c;*s ='\0';// Add a null terminator to mark the end of the string// Loop until the character in the shared memory becomes '*'while(*shm !='*')sleep(1);// Sleep for 1 second before checking again// Detach from the shared memory segment and exit the programshmdt(shm);exit(0);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>#include<stdio.h>#include<stdlib.h>#define SHMSZ 27 // Shared memory sizeintmain(){int shmid;
key_t key;char*shm,*s;
key =5678;// Key used to identify the shared memory segment// Get the identifier of an existing shared memory segmentif((shmid =shmget(key, SHMSZ,0666))<0){perror("shmget");exit(1);}// Attach the shared memory segment to the process's address spaceif((shm =shmat(shmid,NULL,0))==(char*)-1){perror("shmat");exit(1);}// Loop through the shared memory and print its contentsfor(s = shm;*s !='\0'; s++)putchar(*s);putchar('\n');// Print a newline character to separate output// Change the first character in shared memory to '*'*shm ='*';// Detach from the shared memory segment and exit the programshmdt(shm);exit(0);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<stdio.h>intmain(){int fd[2];// File descriptors for the pipe// fd[0] is the read end and fd[1] is the write end of the pipeint child;// Child process indicatorchar input_string[10];// Input string to be sent through the pipeprintf("\nEnter the string to be sent through the pipe: ");scanf("%s", input_string);// Create a pipepipe(fd);// Fork a child process
child =fork();if(!child){// Child processclose(fd[0]);// Close the read end of the pipewrite(fd[1], input_string,5);// Write the input string to the pipe, 5 is the number of byteswait(0);// Wait for the child process to complete}else{// Parent processclose(fd[1]);// Close the write end of the piperead(fd[0], input_string,5);// Read data from the pipeprintf("\nThe string retrieved from the pipe is: %s\n", input_string);}return0;}