#include
#include
#include “scheduler.h”
#include
#include
#include
#include

int sysclk = 0; // system clock
int policy = 0; // 0: FCFS, 1: RR
int time_quota = 0; // time quota for RR
FILE* out;

std::vector jobs;

// print the usage
void usage()
{
printf(“Usage: FCFS
“);
printf(” RR
“);
}

// fork and run the job
int run(Job& job, int timeslice = 100 /* s */)
{
if(job.pid == -100)
job.pid = fork();

if(job.pid 0) // in father process
{
if(job.end >= 0)
{
kill(job.pid, SIGCONT);
fprintf(out, “%d sec: Job %d continued
“, (int)(time(0)-sysclk), job.id);
}
else
{
fprintf(out, “%d sec: Job %d run
“, (int)(time(0)-sysclk), job.id);
}

timeslice *= 1000; // ms
int delta = (timeslice>=100) ? 100 : timeslice;
if(job.duration 0)
{
//printf(“sleep %dms for pid(%d).
“, delta, job.pid);
usleep(delta*1000); // sleep for a while
job.duration -= delta;
job.end = (int)time(0) – sysclk;

if(job.duration =100) ? 100 : timeslice;

int status;
pid_t ret = waitpid(job.pid, &status, WNOHANG);
if(ret < 0) // no such a child
{
job.duration = 0;
fprintf(out, "%d sec: Job %d terminated
", (int)(time(0)-sysclk), job.id);
return -1;
}

if(ret == 0)
continue;

// test if child exited
if (WIFEXITED(status))
{
kill(job.pid, SIGKILL);
job.duration = 0;
fprintf(out, "%d sec: Job %d terminated
", (int)(time(0)-sysclk), job.id);
//printf("%d exited(%d).
", job.pid, WEXITSTATUS(status));
return 0;
}
}

// if the timeslice is exhaused
kill(job.pid, SIGSTOP);
fprintf(out, "%d sec: Job %d suspended
", (int)(time(0)-sysclk), job.id);
return 0;
}
else if (job.pid == 0) // in child process
{
execvp(job.cmds0, job.cmds.data());
exit(-1); // if execvp failed
}
}

// get next word
std::string next(const char*& p)
{
// ignore white char
while(*p==' ' || *p==' ' || *p=='
' || *p=='
')
p++;

if(!*p) return std::string();

const char* q = p;
while(*p && *p!=' ' && *p!=' ' && *p!='
' && *p!='
') p++;
return std::string(q, (unsigned long)p-(unsigned long)q);
}

int read(const char* path)
{
FILE* f = fopen(path, "r");
if(!f)
{
printf("ERROR: failed to open '%s'.
", path);
return -1;
}

char buf1024;
std::vector args;
while(fgets(buf, 1024, f))
{
args.clear();

const char* p = buf;
bool first = true;
for(;;)
{
std::string s = next(p);
if(s.length() = 3)
{
Job j;
j.cmdbuf.reserve(1024);
j.start = atoi(args0.c_str());
j.duration = atoi(argsn-1.c_str())*1000;
for(int i=1; i