Exemple #1
0
/*
 * The program is passed as a vector of strings which is parsed from the text file back in main.
 * I do this in part due to the single responsibility principle. However, the main reason is that
 * it allows me to easily write unit test which exercise the functionality of the CPU.
 * The unit test are likely not include with this assignment.
 */
ComputerSim::ComputerSim(const std::vector<std::string>& program, const int timerInterval) {
    int cpuToMem[2];
    int memToCpu[2];
    tryPipe(cpuToMem, memToCpu);
    int forkResult = tryFork();

    if (isChild(forkResult)) {
        Memory m(cpuToMem[0], memToCpu[1], program);
    } else if (isParent(forkResult)) {
        Cpu c(memToCpu[0], cpuToMem[1], timerInterval);
        waitpid(-1, NULL, 0); // wait for child
    }
}
static void forkSort(int* parentNums, int size, int write_fd)
{
  int fd[2];
  printf("PPid:%ld Pid:%ld Size:%d\n", (long)getppid(), (long)getpid(), size);
  int childNums[size/2], left, right;
  if(size <= 100) //Send sorted array to parent thru pipe
    {
      qsort(parentNums, size, sizeof(int), compare);
      write(write_fd, parentNums, size*sizeof(int));
      exit(0);
    }
  if (pipe(fd)==-1){perror("Failed");}

  printf("Creating child processes...\n");
  size /= 2;

  if(!(left = tryFork()) || !(right = tryFork())) //Children
  {
      if(left)    copy(childNums, parentNums, size);
      else        copy(childNums, parentNums + size, size);
      forkSort(childNums, size, fd[1]);
  }

  /* parent */
  int first[size], second[size], combined[size*2];
  read(fd[0], first, sizeof(first));
  read(fd[0], second, sizeof(second));
  printf("\n\nMerge sorting...  Size:%d\n", size*2);
  mergeSort(first, second, combined, size);
  if(size*2 == SIZE) { //Finished, write to out.dat
    printf("\nFinished!!! (%d)\n\n", size * 2);
    printArray(combined, SIZE);
  }
  else {
    write(write_fd, combined, sizeof(combined));
    exit(0);
  }
}