In: Computer Science
Please do not use vectors or any previously posted code
Write a C++ program which reads in a list of process names and integer times from stdin/cin and simulates round-robin CPU scheduling on the list. The input is a list of lines each consisting of a process name and an integer time, e.g.
ProcessA 4
ProcessB 10
Read line by line until an end-of-transmission (^d) is encountered. You should read the list and represent it in a linked list data structure. You should use the alarm system call to schedule a timer interrupt every 3 seconds. The interrupt handler should pick the next process from the process list, write a message saying how much time it has left to execute,
i.e.
ProcessA 4
Then update its time left to execute by subtracting 3 seconds and return it to the end of the queue. If the process had no time left to execute, you should write a message saying this
i.e.
ProcessA Finished
And delete this process from the linked list.
If there are no processes left to execute, write a message saying
No processes left
And terminate your program.
If further information is needed please specifically comment what is needed.
#include <stdio.h>
#include <bits/stdc++.h>
#include <signal.h>
#include <unistd.h>
using namespace std;
volatile sig_atomic_t print_flag = false;
void handle_alarm( int sig ) {
print_flag = true;
}
int main() {
vector<pair<string,int>> processlist; //vector to
contain the process and time
int n;
cout<<"Enter the number of processes"<<endl;
cin>>n;
cout<<"Enter the processes name and time:
"<<endl;
while (n-->0){
string s;
int t;
cin>>s>>t; // read the process and time
processlist.push_back(make_pair(s,t)); //insert the current process
in the list
}
signal( SIGALRM, handle_alarm ); // Install handler first,
alarm( 2 ); // before scheduling it to be called.
while (1) {
if ( print_flag ) {
if (processlist.size()>0){ //if list has still process
left
if (processlist[0].second<=0){ // if process runs out of
time
cout<<processlist[0].first<<"
Finished"<<endl;
processlist.erase(processlist.begin()); //remove the process from
the list
}
else{ //if process does not run out of time
cout<<processlist[0].first<<"
"<<processlist[0].second<<endl; //print
pair<string,int> pa =
make_pair(processlist[0].first,processlist[0].second-2);
processlist.erase(processlist.begin()); //remove the process from
the front
processlist.push_back(pa); //add the same process with time reduced
by 2 sec at the end of list
}
}
else{ //all processes has been finished
cout<<"No processes left"<<endl;
break;
}
print_flag = false;
alarm( 2 );
}
}
}
OUTPUT: