Saturday, March 7, 2015

Round Robin algorithm in C++

The function bellow should be called using a timer with the desired interval, for example a signal timer like this.

vector<pid_t> backgroundProcs;

void backgroundHandler(){
  static bool locked=false;
  if(locked){
    return;
  }

  locked=true;
  static int running=-1;
  if(backgroundProcs.size()==0){//no processes
    locked=false;
    return;
  }
  int killStatus;
  // Pauses the current process and checks if it is finished
  if(running!=-1 ){
    pid_t pid=backgroundProcs.at(running);
    killStatus=kill(pid,SIGSTOP );
    try{
     int exitError=-1;
     if(isFinished(pid,exitError)){
      if(exitError!=-1){
        printError(exitError);
      }else{
        printPidFinished(pid);
      }
      backgroundProcs.erase(backgroundProcs.begin()+running);
      if(backgroundProcs.size()==0){
        running=-1;
        locked=false;
        return;
      }
    }
  }catch(int ex){
    // Unexpected exception caused on runtime
    // Probably rare since calls on the try block don't usually throw exceptions
    // and backgroundProcs is only accessed by one instance due to the synchronization
    // of the function with the locked variable.
    // No action is required
  }
}
// Picks the next process,loop ends when a process is successfully picked
// or all the processes in the vector are actually finished.
// There is one loop unless there are finished processes in the vector.
do{
  if(running>=backgroundProcs.size()-1){
    running=0;
  }else{
    ++running;
  }
  pid_t pid=backgroundProcs.at(running);
  if(kill(pid,0)==0){
    kill(backgroundProcs.at(running),SIGCONT);
    break;
  }else{
    backgroundProcs.erase(backgroundProcs.begin()+running);
    if(backgroundProcs.size()==0){
      running=-1;
      locked=false;
      return;
    }
  }
}while(true);
locked=false;
}

This is part of the LinuxShell project.

No comments: