-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob.c
63 lines (59 loc) · 1.64 KB
/
job.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "job.h"
#include <stdio.h>
#include <stdlib.h>
// Initialize the jobs table
Jobs_table *init_jobs(void) {
Jobs_table *jobs = (Jobs_table *)malloc(sizeof(Jobs_table));
if (jobs == NULL) {
perror("Failed to allocate memory for jobs table");
exit(EXIT_FAILURE);
}
jobs->list = (Job_t *)malloc(INITIAL_CAPACITY * sizeof(Job_t));
if (jobs->list == NULL) {
perror("Failed to allocate memory for jobs list");
free(jobs);
exit(EXIT_FAILURE);
}
jobs->counter = 0;
jobs->capacity = INITIAL_CAPACITY;
return jobs;
}
void add_job(Jobs_table *jobs, Job_t job) {
if (jobs->counter == jobs->capacity) {
jobs->capacity *= 2;
jobs->list = (Job_t *)realloc(jobs->list, jobs->capacity * sizeof(Job_t));
if (jobs->list == NULL) {
perror("Failed to allocate memory for expanding jobs list");
exit(EXIT_FAILURE);
}
}
jobs->list[jobs->counter] = job;
jobs->counter++;
}
void remove_job(Jobs_table *jobs, Job_t job) {
size_t i;
for (i = 0; i < jobs->counter; ++i) {
if (jobs->list[i].pid == job.pid) {
free(jobs->list[i].command); // Free the command string
// Shift remaining jobs to fill the gap
for (size_t j = i; j < jobs->counter - 1; ++j) {
jobs->list[j] = jobs->list[j + 1];
}
jobs->counter--;
return;
}
}
}
void free_jobs(Jobs_table *jobs) {
for (size_t i = 0; i < jobs->counter; ++i) {
free(jobs->list[i].command);
}
free(jobs->list);
free(jobs);
}
void print_jobs(Jobs_table *jobs) {
Job_t *list = jobs->list;
for (size_t i = 0; i < jobs->counter; i++) {
printf("[%d] %d\t%s\n", list[i].job_id, list[i].pid, list[i].command);
}
}