-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprocess.c
126 lines (106 loc) · 2.52 KB
/
process.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include "shell.h"
#include "utils.h"
#include "process.h"
// processes are stored as a linked list of proc data structures
// internal ids assigned to the processes are in ascending order of
// birth times, only including the processes that are still alive
// thus, they can change if other processes die
// process id is used throughout for unique identification of a process
// LINKED LIST FUNCTIONS
node* insert_head(node* head, proc data) {
node* new = (node*)malloc(sizeof(node));
new->data = data;
if (head == NULL) {
new->next = NULL;
return new;
}
new->next = head;
return new;
}
node* insert_tail(node* head, proc data) {
node* new = (node*)malloc(sizeof(node));
new->data = data;
new->next = NULL;
if (head == NULL) {
return new;
}
node* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = new;
return head;
}
node* delete_node_by_pid(node* head, pid_t pid) {
if (head == NULL) {
return NULL;
}
if (head->data.pid == pid) {
node* temp = head->next;
free(head);
return temp;
}
node* cur = head->next;
node* prev = head;
while (cur != NULL) {
if (cur->data.pid == pid) {
prev->next = cur->next;
free(cur);
return head;
}
prev = cur;
cur = cur->next;
}
return head;
}
proc* get_data_by_pid(node* head, pid_t pid) {
int i = 0;
while (head != NULL) {
i++;
if (head->data.pid == pid) {
head->data.id = i;
return &(head->data);
}
head = head->next;
}
return NULL;
}
proc* get_data_by_id(node* head, int id) {
int i = 0;
while (head != NULL) {
i++;
if (i == id) {
head->data.id = i;
return &(head->data);
}
head = head->next;
}
return NULL;
}
void print_all(node* head) {
int i = 0;
while (head != NULL) {
i++;
printf("[%d] %s %d\n", i, head->data.pname, head->data.pid);
head = head->next;
}
}
// PROCESS FUNCTIONS
void init_processes() {
processes = NULL;
}
proc make_proc (pid_t pid, char* pname) {
proc p;
p.id = -1;
p.pid = pid;
strcpy(p.pname, pname);
return p;
}
int store_process(pid_t pid, char* temp) {
processes = insert_tail(processes, make_proc(pid, temp));
proc* val = get_data_by_pid(processes, pid);
if (val != NULL)
return val->id;
else
return -1;
}