int readTimeSlice(PCB & current, int maxSlice){ int timeSlice; cout << "How long was this process in the CPU: "; cin >> timeSlice; cout << endl; while(!cin || timeSlice < 0 || timeSlice > maxSlice) { cout << "Time must be between 0 and " << maxSlice << "ms" << endl << endl; cout << "How long was this process in the CPU: "; cin.clear(); cin.ignore(100,'\n'); cin >> timeSlice; cout << endl; } current.updateProcessTime(timeSlice); //current.increaseCpuCount(); cout <<"Total CPU Process time has been updated" << endl << endl; cout <<"Current CPU Time is " << current.getTotalProcessTime() << "ms for process " << current.getPID() << endl; cout << endl; return timeSlice; }
PCB* SetupPCB(string name, int priority, int processClass) { if (FindPCB(name) != NULL) { cout << "Process Name already in use" << endl; return NULL; } if (priority > 128 || priority < -127) { cout << "Priority must be between -127 and 128" << endl; return NULL; } if (processClass < 1 || processClass > 2) { cout << "Process Class must either be 1-Application or 2-System" << endl; return NULL; } PCB *pcb = AllocatePCB(); pcb->setProcessName(name); pcb->setPriority(priority); pcb->setProcessClass(processClass); pcb->setState(2); return pcb; }
PCB* PCBList::shortestToCompletion() { PCB* holder = firstNode; PCB* shortestHolder = NULL; int shortestValue; if(firstNode!=NULL) { shortestValue = holder->getTimeRemaining(); shortestHolder = holder; qDebug()<<holder; qDebug()<<shortestValue; while(holder!=NULL) { qDebug()<<holder; qDebug()<<holder->getTimeRemaining(); if(holder->getTimeRemaining()<shortestValue) { shortestValue = holder->getTimeRemaining(); shortestHolder = holder; } holder = holder->nextPCB; } } qDebug()<<shortestValue; qDebug()<<shortestHolder; return shortestHolder; }
//arg1 scheduling algorithm //arg2 quantum, NOTE not all algorithms use quantum //arg3 primary output file name //arg4 secondary output file name //arg5 input data file, NOTE must be well formed //arg6 number of cores, NOTE must be 1 for uniprocessor int main(int argc, char *argv[]) { vector<Process> procs; //hard coded for now unsigned int sim_time = 100000; map<string, SCHED_TYPE> my_map; my_map["FCFS"] = FCFS; my_map["RR"] = RR; my_map["SPN"] = SPN; my_map["SRT"] = SRT; my_map["Feedback"] = Feedback; SCHED_TYPE sched_string = my_map[argv[1]]; unsigned int core_num = atoi(argv[6]); unsigned int quantum = atoi(argv[2]); string filename = argv[3]; string file = argv[4]; string infile = argv[5]; remove(file.c_str()); remove(filename.c_str()); string line; for (int i = 0; i < argc; i++) { cout << argv[i] << " " << endl; } ifstream myfile(infile); if (myfile.is_open()) { while (getline(myfile, line)) { istringstream ss(line); istream_iterator<string> begin(ss); istream_iterator<string> end; vector<string> vstrings(begin, end); vector<pair<string, unsigned int> > bursts; unsigned int PID = atoi(vstrings[0].c_str()); unsigned int arrival_time = atoi(vstrings[2].c_str()); for (unsigned int i = 4; i < vstrings.size(); i += 2) { if (vstrings[i - 1].compare("CPU") == 0) { bursts.push_back(make_pair("CPU", atoi(vstrings[i].c_str()))); } else { bursts.push_back(make_pair("IO", atoi(vstrings[i].c_str()))); } } Process *p = new Process(PID, arrival_time, bursts); procs.push_back(*p); } myfile.close(); } else cout << "Unable to open data file :(" << endl; PCB pcb = PCB(procs, sim_time, sched_string, core_num, quantum, filename); //start running simulation for (unsigned int clock_int = 0; clock_int < pcb.getSimTime(); clock_int++) { pcb.Update(clock_int); if (clock_int % 1000 == 0) cout << "At clock int: " << clock_int << endl; } pcb.writeAdditionalData(file); return 0; }
/* * Simulates the arrival of a new process into the OS. */ void new_process_arrival(PCB new_arrival) { if (new_arrival.check_state("NULL")) return; new_arrival.set_state("NEW"); new_queue.push_back(new_arrival); // A new process enters the system, the display should now update. state_changed_flag = true; }
void MainProcess::Create(str name, int p) { std::vector<str>::iterator it = std::find(nameList.begin(), nameList.end(), name); if (it != nameList.end()){ std::cout << "error "; ss << "error "; return; } if (p > 2){ std::cout << "error "; ss << "error "; return; } else{ //Add the new process name to the list of process names nameList.push_back(name); //Create a reference to a new process PCB* newProcess = new PCB(name, p); //Set the back pointer to the ready list newProcess->setBackPtr(readyList); //Set the parent pointer to the parent process newProcess->setParent(currentlyRunning); //Add it to the process tree currentlyRunning->children.push_back(newProcess); //Add the new process to the ready list newProcess->setStatus(READY); readyList[newProcess->getPriority()].push_back(newProcess); //Call the scheduler Scheduler(); } }
void MainProcess::Destroy(str PID) { //Check for process existence std::vector<str>::iterator findIt = std::find(nameList.begin(), nameList.end(), PID); if (findIt == nameList.end()){ std::cout << "error "; ss << "error "; return; } //Remove from name list nameList.erase(findIt); PCB* temp; //Search the ready list for the PCB with the specified PID for (int i = 1; i < 3; i++){ //for (PCB* p : readyList[i]) for (std::list<PCB*>::iterator it = readyList[i].begin(); it != readyList[i].end(); it++) { if ((*it)->getPID() == PID){ temp = *it; readyList[i].erase(it); KillTree(temp); Scheduler(); return; } } } temp = TreeSearch(PID, &initProcess); if (temp->getPID() != PID){ std::cout << "error "; ss << "error "; return; } KillTree(temp); //Scheduler(); return; }
PCB* FindPCB(string processName) { PCB *temp; queue<PCB*> readyCopy = ready; while (!readyCopy.empty()) { temp = readyCopy.front(); readyCopy.pop(); if (temp->getProcessName() == processName) { return temp; } } queue<PCB*> blockedCopy = blocked; while (!blockedCopy.empty()) { temp = blockedCopy.front(); blockedCopy.pop(); if (temp->getProcessName() == processName) { return temp; } } queue<PCB*> suspendedReadyCopy = suspendedReady; while (!suspendedReadyCopy.empty()) { temp = suspendedReadyCopy.front(); suspendedReadyCopy.pop(); if (temp->getProcessName() == processName) { return temp; } } queue<PCB*> suspendedBlockedCopy = suspendedBlocked; while (!suspendedBlockedCopy.empty()) { temp = suspendedBlockedCopy.front(); suspendedBlockedCopy.pop(); if (temp->getProcessName() == processName) { return temp; } } return NULL; }
//Facilitates the sending of messages between processes // This function is non-blocking int MsgServ::sendMsg(int destPid, MsgEnv* msg) { if(msg != NULL && destPid >= 0 && destPid < PROCESS_COUNT) { //retrieve PCB of currently excecuting process PCB* tempPCB; assure((tempPCB = gRTX->getCurrentPcb()) != NULL,"Failed to retrieve current PCB",__FILE__,__LINE__,__func__,false); //ERic //insert destination and origin into msg envelope msg->setDestPid(destPid); msg->setOriginPid(tempPCB->getId()); _msgTrace->addTrace(msg, SEND); //retrieve destination process PCB PCB* tempDestPCB; assure(gRTX->getPcb(destPid, &tempDestPCB) == EXIT_SUCCESS,"Failed to retrieve dest. PCB",__FILE__,__LINE__,__func__,true); int status = tempDestPCB->getState(); if(status == BLOCKED_MSG_RECIEVE || ( status == SLEEPING && msg->getMsgType() == MsgEnv::REQ_DELAY )) { _scheduler->unblock_process(tempDestPCB); } //determine if process being sent to needs to be made ready //add msg to process mailbox if( msg->getDestPid() != PROC_TIMING && msg->getMsgType() == MsgEnv::REQ_DELAY ) { int type; strToInt(msg->getMsgData(),&type); msg->setMsgType(type); msg->setMsgData(""); } tempDestPCB->addMail(msg); return EXIT_SUCCESS; } return EXIT_ERROR; }
// // New processes are allocated memory in the main_memory array. // void memory_allocate(PCB new_arrival) { int PID = new_arrival.get_id(); int requested_memory = new_arrival.get_size(); int free_memory = 0; while(main_memory[free_memory] != 0) free_memory++; if((MEM_SIZE - free_memory) >= requested_memory) for(int i = free_memory; i < free_memory + requested_memory; i++) main_memory[i] = PID; else { if (DEBUG) cout << "(memory_allocate): ERROR Not enough memory for process " << PID << endl; } // Memory has been allocated, update UI. state_changed_flag = true; }
void OSTest2() //PCB Tests { PCB *a = pcbControl.SetupPCB("a",12,1); PCB *b = pcbControl.SetupPCB("b",-12,2); PCB *c = pcbControl.SetupPCB("c",32,1); PCB *d = pcbControl.SetupPCB("d",34,1); PCB *e = pcbControl.SetupPCB("e",12,2); PCB *f = pcbControl.SetupPCB("f",16,1); PCB *g = pcbControl.SetupPCB("g",12,1); b->setState(3); c->setState(4); d->setState(5); e->setState(3); g->setState(5); pcbControl.InsertPCB(a); pcbControl.InsertPCB(b); pcbControl.InsertPCB(c); pcbControl.InsertPCB(d); pcbControl.InsertPCB(e); pcbControl.InsertPCB(f); pcbControl.showQueue(5); pcbControl.RemovePCB(a); pcbControl.RemovePCB(b); pcbControl.RemovePCB(c); pcbControl.RemovePCB(d); pcbControl.RemovePCB(e); pcbControl.RemovePCB(f); pcbControl.FreePCB(a); pcbControl.FreePCB(b); pcbControl.FreePCB(c); pcbControl.FreePCB(d); pcbControl.FreePCB(e); pcbControl.FreePCB(f); pcbControl.showQueue(5); }
PCB* PCBList::findPCB(QString nameSearch) { PCB* holder; holder = firstNode; if(nameSearch!=NULL) { while(holder!=NULL) { //qDebug()<<"inside while"; if(holder->getName()==nameSearch) { //qDebug()<<"inside if"; //qDebug()<<holder; return holder; } holder = holder->nextPCB; } //qDebug()<<holder; } return NULL; }
PCB* MainProcess::TreeSearch(str pID, PCB* p){ if (p->getPID() != pID){ PCB* temp; if (!p->children.empty()){ for (PCB* q : p->children){ temp = TreeSearch(pID, q); if (temp->getPID() == pID) return temp; } } } return p; }
//Facilitates the retrieval of messages from the process PCB mailbox //This Function is blocking if there are no messages waiting to be recieved MsgEnv* MsgServ::recieveMsg() { //retrieve PCB of currently excecuting process PCB* tempPCB = gRTX->getCurrentPcb(); assure(tempPCB != NULL, "Failed to retrieve current PCB",__FILE__,__LINE__,__func__,false); while (tempPCB->checkMail() == 0) { //i_process cannot be blocked if (tempPCB->getProcessType() == PROCESS_I) return NULL; //block calling process, this automatically calls a process_switch if(gRTX->getCurrentPcb()->getState() != SLEEPING) _scheduler->block_process(BLOCKED_MSG_RECIEVE); } //get mail MsgEnv* tempMsg = tempPCB->retrieveMail(); _msgTrace->addTrace(tempMsg, RECEIVE); return tempMsg; }
PCB* SJFScheduler::schedule(ReadyQueue* q){ PCB* currentProcess; PCB* selectedProcess; //Bring iterator to beginning of ready queue q->begin(); //Intially set current and selected processes to the current process currentProcess = q->getCurrent(); selectedProcess = q->getCurrent(); //Iterate through the ready queue and find the shortest process while(currentProcess != NULL){ if(currentProcess->getTimeRemInBurst() < selectedProcess->getTimeRemInBurst()){ selectedProcess = q->getCurrent(); } currentProcess = q->getNext(); } //Remove the shortest process from the ready queue and return it q->remove(selectedProcess); return selectedProcess; }
void RMS::iniciarEscalonamento() { int tamanho = pronto.ObtemTamanho()+1; NoDaListaSimples<PCB>* aux; while(tamanho > 0) { PCB* maisPrio = pronto.obtemPrimeiro()->ObtemInfo(); int pos = 0; aux = pronto.obtemPrimeiro(); int tamanhoAtual = pronto.ObtemTamanho()+1; for(int i = 0; i < tamanhoAtual; i++) { if(maisPrio->getPeriodo() > aux->ObtemInfo()->getPeriodo()) { maisPrio = aux->ObtemInfo(); pos = i; } aux = aux->ObtemProximo(); } pronto.RetiraDaPosicao(pos); cout << "tamanho atual" << tamanhoAtual << endl; cout << "tamanho total" << tamanho << endl; if(tamanho == tamanhoAtual) { tempo++; executando.AdicionarNoFim(maisPrio); cout << "processo com periodo exec "<<maisPrio->getPeriodo() << endl; cout << "processo tem " << maisPrio->getExec() << endl; maisPrio->decremento(); cout << "processo foi decrementado e tem " << maisPrio->getExec() << endl; if(maisPrio->getExec() == 0) { cout << "processo acabou" << endl; terminado.AdicionarNoFim(maisPrio); executando.Retirar(); tamanho--; } else { cout << "voltou para pronto" << endl; pronto.AdicionarNoFim(maisPrio); } //cout << "pos que vai ser tirada" << pos<< endl; //cout << maisPrio->getPeriodo(); } } }
// // Processes that are finished running have their memory removed. // Remaining memory is then shifted down. // void memory_deallocate(PCB finished_process) { int i = 0; int j; int PID = finished_process.get_id(); while(main_memory[i] != PID) i++; j = i; while(main_memory[j] == PID) { main_memory[j] = 0; j++; } while(main_memory[j] != 0 && j < MEM_SIZE) { main_memory[i] = main_memory[j]; main_memory[j] = 0; i++; j++; } // Memory has been deallocated, update UI. state_changed_flag = true; }
bool sortHelp (PCB i,PCB j) { return (i.getProcessSize()<j.getProcessSize()); }
int main(int argc, const char * argv[]) { int printerNum; int cdrwNum; int diskNum; int timeSlice; int terminatedProcessCount = 0; int terminatedProcessTotalTime = 0; float totalAveTerminatedCpuTime = 0; //int cylinderNum; int systemPID = 0; int totalMemSize = 0; int processSize = 0; int roundedProcessSize = 0; int maxProcessSize; int pageSize = 0; int freeMem = 0; int usedMem = 0; pair<bool, int> activeRecord; string userInput; vector<int> cylinderNum; vector<deque<PCB> > printers; vector<FscanDiskQueue> disks; vector<deque<PCB> > cdrws; vector<pair<bool, int>> frameList; deque<PCB> printerQueue; FscanDiskQueue diskQueue; deque<PCB> cdrwQueue; deque<PCB> readyQueue; deque<PCB> jobPool; printWelcome(); cout << "*************SYS GEN***************" << endl; //SYS GEN***************************************** //************TotalMemSize**************** cout << "What is the total Memory Size: "; cin >> totalMemSize; cout << endl; while((!cin || totalMemSize < 1|| (totalMemSize == 0)) || !memContraintCheck(totalMemSize) ) { cout << "Invalid Input!" << endl; cout << "Total Memory Size should be divisible by a power of 2" << endl << endl; cout << "What is the total Memory Size: "; cin.clear(); cin.ignore(100,'\n'); cin >> totalMemSize; cout << endl; } cout << " The Total Memory Size is " << totalMemSize << " Words" << endl; cout << endl; //************MaxProcessSize**************** cout << "What is the Max Process Size: "; cin >> maxProcessSize; cout << endl; while(!cin || maxProcessSize < 1 || maxProcessSize > totalMemSize) { cout << "Invalid Input!" << endl; cout << "Max Process size must be less than Total Memory Size." << endl; cout << "What is the Max Process Size: "; cin.clear(); cin.ignore(100,'\n'); cin >> maxProcessSize; cout << endl; } cout << " The Max Process Size is " << maxProcessSize << " Words" << endl; cout << endl; //************PageSize**************** cout << "What is the Page Size(Powers of 2 only): "; cin >> pageSize; cout << endl; while(!cin || pageSize < 1 || totalMemSize % pageSize != 0 || (pageSize == 0) || (pageSize & (pageSize - 1)) ) { cout << "Invalid Input!" << endl; cout << "Page Size must be a power of 2 and divide Memory evenly" << endl << endl; cout << "What is the Page Size: "; cin.clear(); cin.ignore(100,'\n'); cin >> pageSize; cout << endl; } cout << " The Page Size is " << pageSize << " Words" << endl; cout << endl; //cout << "Total Memory size must be deivisible by" << endl; //************Timeslice**************** cout << "How long is a time slice (in milliseconds): "; cin >> timeSlice; cout << endl; while(!cin || timeSlice < 1) { cout << "Invalid Input!" << endl; cout << "How long is a time slice (in milliseconds) "; cin.clear(); cin.ignore(100,'\n'); cin >> timeSlice; cout << endl; } cout << " A Timeslice is " << timeSlice << " milliseconds" << endl; cout << endl; //**************Printers************** cout << "How Many Printers would you like: "; cin >> printerNum; cout << endl; while(!cin || printerNum < 1) { cout << "Invalid Input!" << endl; cout << "How Many Printers: "; cin.clear(); cin.ignore(100,'\n'); cin >> printerNum; cout << endl; } cout << printerNum << " Printers added" << endl; cout << endl; //*************Disks*************** cout << "How Many Disks would you like: "; cin >> diskNum; cout << endl; while(!cin || diskNum < 1) { cout << "Invalid Input!" << endl; cout << "How Many Disks: "; cin.clear(); cin.ignore(100,'\n'); cin >> diskNum; cout << endl; } cout << diskNum << " Disks added" << endl; cout << endl; //**************Cylinders************** for (int i = 0; i < diskNum; i++) { cout << "How Many Cylinders does disk " << i + 1 << " have: "; int cylNum; cin >> cylNum; cout << endl; while(!cin || cylNum < 1) { cout << "Invalid Input!" << endl; cout << "How Many Cylinders: "; cin.clear(); cin.ignore(100,'\n'); cin >> cylNum; cout << endl; } cylinderNum.push_back(cylNum); } for (int i = 0 ; i < diskNum; i++) { cout << "Disk " << i+1 << " has " << cylinderNum[i] << " cylinders" << endl; } //cout << "Each Disk has " << cylinderNum << " Cylinders" << endl; cout << endl; //*************CDRW*************** cout << "How Many CD/RWs would you like: "; cin >> cdrwNum; cout << endl; while(!cin || cdrwNum < 1) { cout << "Invalid Input!" << endl; cout << "How Many CD/RWs: "; cin.clear(); cin.ignore(100,'\n'); cin >> cdrwNum; cout << endl; } cout << cdrwNum << " CD/RWs added" << endl; cout << endl; //*************MakeQueuesAndFrameList*************** for (int i = 0; i < printerNum+1; i++) { printers.push_back(printerQueue); } for (int i = 0; i < diskNum+1; i++) { disks.push_back(diskQueue); } for (int i = 0; i < cdrwNum+1; i++) { cdrws.push_back(cdrwQueue); } int totalFrames = totalMemSize / pageSize; activeRecord.first = false; for (int i = 0; i< totalFrames; i++) { frameList.push_back(activeRecord); } cout << "*************STARTING OS***************" << endl; //RUNNING***************************************** try { while (true) { try { userInput = ""; cout << "Commands examples: {A, S, t, T, p1, d2, c3, P3, D2, C1}" << endl; cout << '>' ; cin >> userInput; cout << endl; if (userInput == "q" || userInput == "Q") { throw -1; } //ADD PROCESSES***************************************** if (userInput == "A") { cout << "What is the size of the Process: "; cin >> processSize; cout << endl; while(!cin || processSize < 1 ) { cout << "Invalid Input!" << endl; cout << "Max Process Size is " << maxProcessSize << endl; cout << "What is the size of the Process: " << endl; cin.clear(); cin.ignore(100,'\n'); cin >> processSize; cout << endl; } if (processSize > maxProcessSize ) { cout << "Process is too large and has been rejected." << endl << endl; } else{ cout << " The Process Size is " << processSize << endl; cout << endl; PCB newProcess(systemPID); newProcess.setProcessSize(processSize); if ((usedMem + processSize) <= totalMemSize) { readyQueue.push_back(newProcess); cout << "Process added to ready queue" << endl << endl; if (processSize % pageSize == 0) { usedMem += processSize; freeMem = totalMemSize - usedMem; } else{ roundedProcessSize = ((processSize / pageSize) + 1) * pageSize; usedMem += roundedProcessSize; freeMem = totalMemSize - usedMem; } //usedMem += processSize; //freeMem = totalMemSize - usedMem; cout << "Free Memory: " << freeMem << endl; cout << "Used Memory: " << usedMem << endl << endl; int framesNeeded; if (processSize % pageSize == 0) { framesNeeded = processSize/pageSize; } else{ framesNeeded = (processSize/pageSize) + 1; } int i = 0; int j = 0; while (j < framesNeeded) { if (frameList[i].first == false) { frameList[i].first = true; frameList[i].second = readyQueue.back().getPID(); readyQueue.back().updateFrames(i); j++; } i++; } } else{ jobPool.push_back(newProcess); sort(jobPool.begin(), jobPool.end(), sortHelp); cout << "Process added to Job Pool" << endl << endl; cout << "Free Memory: " << freeMem << endl; cout << "Used Memory: " << usedMem << endl << endl; } systemPID++; } } //SNAPSHOTS***************************************** else if(userInput == "S"){ do{ cout << "Please choose the snapshot you'd like:" << endl; cout << "'r', 'p', 'd', 'c', or 'm' : "; cin >> userInput; cout << endl; } while (userInput != "r" && userInput != "p" && userInput != "d" && userInput != "c" && userInput != "m"); //READY QUEUE PRINT***************************************** if (userInput == "r") { cout << endl << "READY QUEUE" << endl; printListHeader(totalAveTerminatedCpuTime, freeMem, usedMem); for (int i = 0; i < readyQueue.size(); i++) { float aveBurst = 0; if (readyQueue[i].getCpuCount() > 0) { aveBurst = ((float)readyQueue[i].getTotalProcessTime())/readyQueue[i].getCpuCount(); } cout << left << " " << setw(5) << readyQueue[i].getPID() << left << "| " << setw(9) << "N/A" << left << "| " << setw(8) << "N/A" << left << "| " << setw(9) << "N/A" << left << "| " << setw(5) << "N/A" << left << "| " << setw(8) << "N/A" << left << "| " << setw(6) << "N/A" << left << "| " << setw(6) << readyQueue[i].getTotalProcessTime() << left << "| " << setw(10) << readyQueue[i].getAveBurstTime() << left << "| "; readyQueue[i].printFrames(); //cout << readyQueue[i].getPID() << endl; } cout <<" ---------------------------------------------------------------------------------------------"<<endl; cout << endl; cout << "Job Pool PID numbers: "; if (!jobPool.empty()) { for (int i = 0 ; i < jobPool.size(); i++) { cout << "PID " << jobPool[i].getPID() << " "; } } else{ cout << "Empty"; } cout << endl << endl; } //MEMORY PRINT***************************************** else if (userInput == "m") { cout << endl << "MEMORY INFORMATION" << endl << endl; cout << "-------------------" << endl; cout << left << "| " << setw(6) << "Frame " << left << "| " << setw(6) << "Process |" << endl; cout << "-------------------" << endl; for (int i = 0 ; i < frameList.size(); i++) { if (frameList[i].first == true) { cout << left << "| " << setw(6) << i << left << "| " << setw(7) << frameList[i].second << " |" << endl; //cout << "Frame | " << i << " Process |" << frameList[i].second << " |" << endl; } } cout << "-------------------" << endl << endl; cout << "Free Frames: "; for (int i = 0 ; i < frameList.size(); i++) { if (frameList[i].first == false) { cout << i << " "; } } cout << endl << endl; } //PRINTER QUEUE PRINT***************************************** else if (userInput == "p") { cout << endl << "PRINTER QUEUE" << endl; printListHeader(totalAveTerminatedCpuTime, freeMem, usedMem); for (int i = 1; i < printers.size(); i++) { cout << " --"<< "p" << i << endl; //<<"--------------------------------------------------------------------"<< endl; for (int j = 0; j < printers[i].size(); j++) { cout << printers[i][j]; } } cout <<" ---------------------------------------------------------------------------------------------"<<endl; cout << endl; } //DISK QUEUE PRINT***************************************** else if (userInput == "d") { cout << endl << "DISK QUEUE" << endl; printListHeader(totalAveTerminatedCpuTime, freeMem, usedMem); for (int i = 1; i < disks.size(); i++) { cout << " --"<< "d" << i << endl; //<<"--------------------------------------------------------------------" << endl; disks[i].printDiskQueue(); } cout <<" ---------------------------------------------------------------------------------------------"<<endl; cout << endl; } //CDRW QUEUE PRINT***************************************** else if (userInput == "c") { cout << endl << "CDRW QUEUE" << endl; printListHeader(totalAveTerminatedCpuTime, freeMem, usedMem); for (int i = 1; i < cdrws.size(); i++) { cout << " --"<< "c" << i << endl; //<<"--------------------------------------------------------------------" << endl; for (int j = 0; j < cdrws[i].size(); j++) { cout << cdrws[i][j]; } } cout <<" ---------------------------------------------------------------------------------------------"<<endl; cout << endl; } else{ throw userInput; } } //TERMINATE PROCESS***************************************** else if(userInput == "t"){ if (readyQueue.empty()) { cout << "The Ready Queue is empty" << endl << endl; } else{ readTimeSlice(readyQueue.front(), timeSlice); cout << "Terminating Process " << readyQueue.front().getPID() << endl; cout << "Total CPU time was " << readyQueue.front().getTotalProcessTime() << endl; terminatedProcessCount++; terminatedProcessTotalTime += readyQueue.front().getTotalProcessTime(); if (readyQueue.front().getProcessSize() % pageSize == 0) { usedMem = usedMem - readyQueue.front().getProcessSize(); freeMem = totalMemSize - usedMem; } else{ roundedProcessSize = ((readyQueue.front().getProcessSize() / pageSize) + 1) * pageSize; usedMem = usedMem - roundedProcessSize; freeMem = totalMemSize - usedMem; } cout << "Free Memory: " << freeMem << endl; cout << "Used Memory: " << usedMem << endl; vector<int> frames = readyQueue.front().getFrames(); for (int i = 0 ; i < frames.size() ; i++) { frameList[frames[i]].first = false; } readyQueue.pop_front(); cout << endl; totalAveTerminatedCpuTime = (float)terminatedProcessTotalTime/terminatedProcessCount; int i = 0; while (!jobPool.empty() && jobPool.front().getProcessSize() < freeMem ) { while (jobPool.back().getProcessSize() > freeMem && i < jobPool.size()) { jobPool.push_front(jobPool.back()); jobPool.pop_back(); i++; } if (jobPool.back().getProcessSize() < freeMem) { readyQueue.push_back(jobPool.back()); jobPool.pop_back(); cout << "Process " << readyQueue.back().getPID() << " added to Ready Queue" << endl; int framesNeeded; if (processSize % pageSize == 0) { framesNeeded = processSize/pageSize; } else{ framesNeeded = (processSize/pageSize) + 1; } int i = 0; int j = 0; while (j < framesNeeded) { if (frameList[i].first == false) { frameList[i].first = true; frameList[i].second = readyQueue.back().getPID(); readyQueue.back().updateFrames(i); j++; } i++; } if (readyQueue.back().getProcessSize() % pageSize == 0) { usedMem = usedMem + readyQueue.back().getProcessSize(); freeMem = totalMemSize - usedMem; } else{ roundedProcessSize = ((readyQueue.back().getProcessSize() / pageSize) + 1) * pageSize; usedMem += roundedProcessSize; freeMem = totalMemSize - usedMem; } cout << "Free Memory: " << freeMem << endl; cout << "Used Memory: " << usedMem << endl; i = 0; } sort(jobPool.begin(), jobPool.end(), sortHelp); } } } //MOVETOBACKOFQUEUE****************************** else if(userInput == "T"){ if (readyQueue.empty()) { cout << "The Ready Queue is empty" << endl << endl; } else{ cout << "Moving Process " << readyQueue.front().getPID() << " to back of the Ready Queue " << endl << endl; readyQueue.push_back(readyQueue.front()); readyQueue.pop_front(); readyQueue.back().updateProcessTime(timeSlice); cout <<"Total CPU Process time has been updated" << endl << endl; cout <<"Current CPU Time is " << readyQueue.back().getTotalProcessTime() << "ms for Process " << readyQueue.back().getPID() << endl; cout << endl; } } //KILL PROCESS ANYWHERE***************************************** else if(userInput[0] == 'K'){ userInput.erase(0,1); if (checkValidNum(userInput, systemPID - 1) || stoi(userInput) == 0) { PCB temp(-1); int i = 0; bool found = false; int searchPID = stoi(userInput); //READY QUEUE KILL*************************************** while (i < readyQueue.size() && found == false) { cout << "Searching Ready Queue" << endl; if (searchPID == readyQueue[i].getPID()) { temp = readyQueue[i]; readyQueue.erase(readyQueue.begin()+i); found = true; cout << "Found the Process in the Ready Queue" << endl << endl; if (i == 0) { readTimeSlice(temp, timeSlice); } } i++; } //PRINT KILL********************************************* if (found == false) { for (int i = 1; i < printers.size(); i++) { for (int j = 0; j < printers[i].size(); j++) { cout << "Searching Print Queues" << endl; if (searchPID == printers[i][j].getPID()) { temp = printers[i][j]; printers[i].erase(printers[i].begin() + j); found = true; cout << "Found the Process in the Print Queue" << endl << endl; } } } } //DISK KILL********************************************* if (found == false) { for (int i = 1; i < disks.size(); i++) { if (disks[i].findProcess(searchPID)) { temp = disks[i].killProcess(searchPID); } } } //CDRW KILL********************************************* if (found == false) { for (int i = 1; i < cdrws.size(); i++) { for (int j = 0; j < cdrws[i].size(); j++) { cout << "Searching CDRW Queue" << endl; if (searchPID == cdrws[i][j].getPID()) { temp = cdrws[i][j]; cdrws[i].erase(cdrws[i].begin() + j); found = true; cout << "Found the Process in the CDRW Queue" << endl << endl; } } } } //CLEAN UP FOR NON JOB POOL if (found == true) { //readTimeSlice(temp, timeSlice); cout << "Killing Process " << temp.getPID() << endl; cout << "Total CPU time was " << temp.getTotalProcessTime() << endl; terminatedProcessCount++; terminatedProcessTotalTime += temp.getTotalProcessTime(); if (temp.getProcessSize() % pageSize == 0) { usedMem = usedMem - temp.getProcessSize(); freeMem = totalMemSize - usedMem; } else{ roundedProcessSize = ((temp.getProcessSize() / pageSize) + 1) * pageSize; usedMem = usedMem - roundedProcessSize; freeMem = totalMemSize - usedMem; } cout << "Free Memory: " << freeMem << endl; cout << "Used Memory: " << usedMem << endl; vector<int> frames = temp.getFrames(); for (int i = 0 ; i < frames.size() ; i++) { frameList[frames[i]].first = false; } cout << endl; totalAveTerminatedCpuTime = (float)terminatedProcessTotalTime/terminatedProcessCount; i = 0; while (!jobPool.empty() && jobPool.front().getProcessSize() <= freeMem ) { while (jobPool.back().getProcessSize() > freeMem && i < jobPool.size()) { jobPool.push_front(jobPool.back()); jobPool.pop_back(); i++; } if (jobPool.back().getProcessSize() <= freeMem) { readyQueue.push_back(jobPool.back()); jobPool.pop_back(); cout << "Process " << readyQueue.back().getPID() << " added to Ready Queue" << endl; int framesNeeded; if (processSize % pageSize == 0) { framesNeeded = processSize/pageSize; } else{ framesNeeded = (processSize/pageSize) + 1; } int i = 0; int j = 0; while (j < framesNeeded) { if (frameList[i].first == false) { frameList[i].first = true; frameList[i].second = readyQueue.back().getPID(); readyQueue.back().updateFrames(i); j++; } i++; } if (readyQueue.back().getProcessSize() % pageSize == 0) { usedMem = usedMem + readyQueue.back().getProcessSize(); freeMem = totalMemSize - usedMem; } else{ roundedProcessSize = ((readyQueue.back().getProcessSize() / pageSize) + 1) * pageSize; usedMem += roundedProcessSize; freeMem = totalMemSize - usedMem; } cout << "Free Memory: " << freeMem << endl; cout << "Used Memory: " << usedMem << endl; i = 0; } sort(jobPool.begin(), jobPool.end(), sortHelp); } } //JOB POOL KILL********************************************* if (found == false) { for (int i = 0; i < jobPool.size(); i++) { if (searchPID == jobPool[i].getPID()) { cout << "Searching Job Pool" << endl; PCB temp = jobPool[i]; jobPool.erase(jobPool.begin() + i); found = true; cout << "Found the Process in the Job Pool" << endl << endl; cout << "Killing Process " << temp.getPID() << endl << endl; terminatedProcessCount++; } } } if (found == false) { cout << "PID not found" << endl << endl; } } else{ cout << "PID does not exist" << endl << endl; } } //ADD TO PRINTER QUEUE***************************************** else if(userInput[0] == 'p'){ userInput.erase(0,1); if (checkValidNum(userInput, printerNum)) { if (!readyQueue.empty()) { readyQueue.front().fillPCB('p', false, 0,pageSize); printers[stoi(userInput)].push_back(readyQueue.front()); readyQueue.pop_front(); readTimeSlice(printers[stoi(userInput)].back(), timeSlice); printers[stoi(userInput)].back().increaseCpuCount(); } else{ cout << "There are no available processes in the Ready Queue" << endl; cout << "Please populate the Ready Queue and try again" << endl << endl; } } else{ cout << "Printer does not exist" << endl << endl; } } //ADD TO DISK QUEUE***************************************** else if(userInput[0] == 'd'){ userInput.erase(0,1); if (checkValidNum(userInput,diskNum)) { if (!readyQueue.empty()) { readyQueue.front().fillPCB('d', true, cylinderNum[stoi(userInput)-1], pageSize); readTimeSlice(readyQueue.front(), timeSlice); readyQueue.front().increaseCpuCount(); disks[stoi(userInput)].push_back(readyQueue.front()); readyQueue.pop_front(); } else{ cout << "There are no available processes in the Ready Queue" << endl; cout << "Please populate the Ready Queue and try again" << endl << endl; } } else{ cout << "Printer does not exist" << endl << endl; } } //ADD TO CDRW QUEUE***************************************** else if(userInput[0] == 'c'){ userInput.erase(0,1); if (checkValidNum(userInput,cdrwNum)) { if (!readyQueue.empty()) { readyQueue.front().fillPCB('c', false, 0, pageSize); cdrws[stoi(userInput)].push_back(readyQueue.front()); readyQueue.pop_front(); readTimeSlice(cdrws[stoi(userInput)].back(), timeSlice); cdrws[stoi(userInput)].back().increaseCpuCount(); } else{ cout << "There are no available processes in the Ready Queue" << endl; cout << "Please populate the Ready Queue and try again" << endl << endl; } } else{ cout << "CDRW does not exist" << endl << endl; } } //REMOVE FROM PRINTER QUEUE***************************************** else if(userInput[0] == 'P'){ userInput.erase(0,1); if (userInput.length()<1) { throw userInput; } if (checkValidNum(userInput, printerNum)) { if (printers[stoi(userInput)].empty()) { cout << "Printer Queue is empty" << endl << endl; } else{ readyQueue.push_back(printers[stoi(userInput)].front()); printers[stoi(userInput)].pop_front(); cout << "Printer Interrupt Handled" << endl << endl; } } else{ cout << "Printer does not exist" << endl << endl; } } //REMOVE FROM DISK QUEUE***************************************** else if(userInput[0] == 'D'){ userInput.erase(0,1); if (userInput.length()<1) { throw userInput; } if (checkValidNum(userInput, diskNum)) { if (disks[stoi(userInput)].empty()) { cout << "Disk Queue is empty" << endl << endl; } else{ readyQueue.push_back(disks[stoi(userInput)].front()); disks[stoi(userInput)].pop_front(); cout << "Disk Interrupt Handled" << endl << endl; } } else{ cout << "Disk does not exist" << endl << endl; } } //REMOVE FROM CDRW QUEUE***************************************** else if(userInput[0] == 'C'){ userInput.erase(0,1); if (userInput.length()<1) { throw userInput; } if (checkValidNum(userInput, cdrwNum)) { if (cdrws[stoi(userInput)].empty()) { cout << "CDRW Queue is empty" << endl << endl; } else{ readyQueue.push_back(cdrws[stoi(userInput)].front()); cdrws[stoi(userInput)].pop_front(); cout << "CD/RW Interrupt Handled" << endl << endl; } } else{ cout << "CDRW does not exist" << endl << endl; } } else{ throw userInput; } } catch (string) { cout << "Input error: Please try again" << endl << endl; } //cout << endl; }
void system_call_handler(LinkedList<PCB> *device_array, LinkedList<PCB> &ready_queue, int device_num, string device_type, int array_size) { string file_name; int file_size, location; char file_op; PCB vessel; file file_parameters; if(device_num > array_size) { cout << "error: " << device_type << " number exceeded." << endl; return; } else if (device_num == 0){ cout << "error: " << device_type << " has no value " << device_num << " amount." << endl; return; } else if(ready_queue.IsEmpty()) { cout << "No processes in ready queue" << endl; return; } vessel = ready_queue.peek(); ready_queue.deQueue(); cout << "Sending the first object to a printer queue" << endl; cout << "Enter the file name: "; while( file_name.length() == 0 || file_name.length() > 16) { cin >> file_name; if(file_name.length() > 16) { cout << "Please reenter your file; input too long." << endl; } else if(file_name.length() == 0) cout << "No input detected. Try again." << endl; } cout << endl; cout << "Enter the file size: "; cin >> file_size; cout << endl; cout << "Enter the file location: "; cin >> location; cout << endl; cout << "Enter the file operation: "; if(device_type == "printers"){ cout << "Printer op; setting operation to (w)rite." << endl; file_op = 'w'; } else{ cin >> file_op; newLine(); cout << endl; while(file_op != 'r' && file_op != 'w') { cout << "Please enter r for read or w for write: " << endl; cin >> file_op; newLine(); } } cout << "parameters are: " << file_name << " " << file_size << " " << location << " " << file_op << endl; file_parameters.change_parameters(file_name, file_op, file_size, location); vessel.file_parameters(file_parameters); cout << "going into device number: " << device_num << endl; admit_into_queue(device_array[device_num - 1], vessel); }
void OS::start() { // Get the s files system("ls *.s > progs"); fstream readProgs; readProgs.open("progs", ios::in); if (!readProgs.is_open()) { cout << "cant open progs\n"; exit(1); } string line; getline(readProgs, line); while (!readProgs.eof()) { as.assemble(line); // assemble the files //make the PCB for each file, put the jobs list, and then the ready queue PCB * p = new PCB; jobs.push_back(p); readyQ.push(p); p->state = "ready"; string fileName = line.erase(line.length() -2, 2); // assign file names, input and outputs p->originalfilename = fileName + ".o"; p->readfilename = fileName + ".in"; p->writefilename = fileName + ".out"; p->stfilename = fileName + ".st"; // Read in files p->openReadInFileStream(); p->openWriteOutFileStream(); //read into mem int base, limit; vm.loadIntoMemory(p->originalfilename, &base, &limit); p->base = base; p->limit = limit; p->pc = base; getline(readProgs, line); } readProgs.close(); system("rm progs"); // copy item 1 in readyQueue to running , load pcb data to vm running = readyQ.front(); readyQ.pop(); givePCBToVM(); int code = 0; while (!done()) // main loops { code = 0; vm.run(); code = vm.sr; code = code & 0xe0; code >>= 5; masterClock += 5; contextSwitchClock += 5; for (list<PCB *>::iterator it = jobs.begin(); it != jobs.end(); it++) if(!strcmp((*it)->state.c_str(), "terminated")) (*it)->contextSwitchTime += 5; // if interrupt move. if(!waitQ.empty()) { while (waitQ.front()->interruptTime <= masterClock) { PCB * temp = waitQ.front(); waitQ.pop(); readyQ.push(temp); temp->state = "ready"; if(waitQ.empty()) break; } } for (list<PCB *>::iterator it = jobs.begin(); it != jobs.end(); it++) if(strcmp((*it)->state.c_str(), "ready")) (*it)->waitingTime += vm.clock; if(!(running == NULL)) { //update clocks masterClock += vm.clock; running->cpuTime += vm.clock; //them errors cases switch (code) { case 0: getPCBFromVM(); readyQ.push(running); break; case 1: running->state = "terminated"; break; case 2: running->state = "terminated"; outputErrorCode("Out-of-Bound Reference"); break; case 3: running->state = "terminated"; outputErrorCode("Stack Overflow"); break; case 4: running->state = "terminated"; outputErrorCode("Stack Underflow"); break; case 5: running->state = "terminated"; outputErrorCode("Invalid OPCode"); break; case 6: { int readIn; running->readIntoRegister >> readIn; int readReg = vm.sr; readReg &= 0x300; readReg >>= 8; if(readReg < 0 || readReg > 3) { outputErrorCode("Invalid IO Register"); break; } vm.reg[readReg] = readIn; masterClock++; running->ioTime += 27; running->cpuTime++; waitQ.push(running); running->state = "waiting"; getPCBFromVM(); running->interruptTime = masterClock + 28; break; } case 7: { int writeToReg = vm.sr; writeToReg &= 0x300; writeToReg >>= 8; int temp = vm.reg[writeToReg] & 0x8000; if (temp) temp = vm.reg[writeToReg] | 0xffff0000; else temp = vm.reg[writeToReg] & 0xffff; running->writeToRegister << temp << endl; masterClock++; running->ioTime += 27; running->cpuTime++; waitQ.push(running); running->state = "waiting"; getPCBFromVM(); running->interruptTime = masterClock + 28; break; } default: outputErrorCode("Invalid Return Code"); running->state = "terminated"; break; } running = NULL; } //update clock after item 1 if(readyQ.empty() && !waitQ.empty()) { int temp = waitQ.front()->interruptTime - masterClock; masterClock += temp; idleClock += temp; readyQ.push(waitQ.front()); waitQ.front()->state = "ready"; waitQ.pop(); for (list<PCB *>::iterator it = jobs.begin(); it != jobs.end(); it++) if(!strcmp((*it)->state.c_str(), "terminated")) (*it)->idleTime += temp; } if(!readyQ.empty()) { running = readyQ.front(); running->state = "running"; readyQ.pop(); givePCBToVM(); } }
void OS::start() { // read in all the .s files system("ls *.s > progs"); fstream readProgs; readProgs.open("progs", ios::in); if (!readProgs.is_open()) { cout << "could not open progs.\n"; exit(1); } string line; getline(readProgs, line); //begin while loops when !progs end of file while (!readProgs.eof()) { as.assemble(line); // assemble each file using the asembler //create PCB for each file, put in jobs list, and put in ready queue PCB * p = new PCB; jobs.push_back(p); readyQ.push(p); p->state = "ready"; string fileName = line.erase(line.length() -2, 2); // set file names for input and output p->originalfilename = fileName + ".o"; p->readfilename = fileName + ".in"; p->writefilename = fileName + ".out"; p->stfilename = fileName + ".st"; // Open input and output file streams in PCB p->openReadInFileStream(); p->openWriteOutFileStream(); //read into memory, modify PCB with values for base and limit int base, limit; vm.loadIntoMemory(p->originalfilename, &base, &limit); p->base = base; p->limit = limit; p->pc = base; getline(readProgs, line); } // end reading into memory readProgs.close(); system("rm progs"); // copy first item in readyQ to running , load pcb data to vm running = readyQ.front(); readyQ.pop(); givePCBToVM(); int code = 0; while (!done()) // main while loop main processing { code = 0; vm.run(); // runs current process in vm, returns error code stored for later // get return code from status register code = vm.sr; code = code & 0xe0; code >>= 5; // update clocks for context switch masterClock += 5; contextSwitchClock += 5; // update all processes that aren't terminated with addition to context switch time for (list<PCB *>::iterator it = jobs.begin(); it != jobs.end(); it++) if(!strcmp((*it)->state.c_str(), "terminated")) (*it)->contextSwitchTime += 5; // First item in main loop // move items from waitQ into readyQ if interrupt time hit if(!waitQ.empty()) { while (waitQ.front()->interruptTime <= masterClock) { PCB * temp = waitQ.front(); waitQ.pop(); readyQ.push(temp); temp->state = "ready"; if(waitQ.empty()) break; } } // Second item in main loop // Update waiting time for all items in ready queue with latest cycle time from vm.run() for (list<PCB *>::iterator it = jobs.begin(); it != jobs.end(); it++) if(strcmp((*it)->state.c_str(), "ready")) (*it)->waitingTime += vm.clock; if(!(running == NULL)) { // update master clock and cpu time masterClock += vm.clock; running->cpuTime += vm.clock; // main switch to handle return code, if terminated set, output errorcode. switch (code) { case 0: getPCBFromVM(); readyQ.push(running); break; case 1: running->state = "terminated"; break; case 2: running->state = "terminated"; outputErrorCode("Out-of-Bound Reference"); break; case 3: running->state = "terminated"; outputErrorCode("Stack Overflow"); break; case 4: running->state = "terminated"; outputErrorCode("Stack Underflow"); break; case 5: running->state = "terminated"; outputErrorCode("Invalid OPCode"); break; case 6: { int readIn; running->readIntoRegister >> readIn; int readReg = vm.sr; readReg &= 0x300; readReg >>= 8; if(readReg < 0 || readReg > 3) { outputErrorCode("Invalid IO Register"); break; } vm.reg[readReg] = readIn; masterClock++; running->ioTime += 27; running->cpuTime++; waitQ.push(running); running->state = "waiting"; getPCBFromVM(); running->interruptTime = masterClock + 28; break; } case 7: { int writeToReg = vm.sr; writeToReg &= 0x300; writeToReg >>= 8; int temp = vm.reg[writeToReg] & 0x8000; if (temp) temp = vm.reg[writeToReg] | 0xffff0000; else temp = vm.reg[writeToReg] & 0xffff; running->writeToRegister << temp << endl; masterClock++; running->ioTime += 27; running->cpuTime++; waitQ.push(running); running->state = "waiting"; getPCBFromVM(); running->interruptTime = masterClock + 28; break; } default: outputErrorCode("Invalid Return Code"); running->state = "terminated"; break; } running = NULL; } // end if running loop // Third item in main loop // if all items in waitQ, update masterclock to get first item out of waitQ if(readyQ.empty() && !waitQ.empty()) { int temp = waitQ.front()->interruptTime - masterClock; masterClock += temp; idleClock += temp; readyQ.push(waitQ.front()); waitQ.front()->state = "ready"; waitQ.pop(); // update idle time for all non terminated process in jobs list for (list<PCB *>::iterator it = jobs.begin(); it != jobs.end(); it++) if(!strcmp((*it)->state.c_str(), "terminated")) (*it)->idleTime += temp; } // move next process from readyQ into running state, copy over pcb contents if(!readyQ.empty()) { running = readyQ.front(); running->state = "running"; readyQ.pop(); givePCBToVM(); } } // end main process loop