forked from ejamesc/CS2106-process-manager
/
manager.go
493 lines (437 loc) · 10.5 KB
/
manager.go
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package main
import (
"fmt"
"bufio"
"flag"
"os"
"io"
"path"
"strings"
"strconv"
"container/list"
)
/* Matriculation number: U096996N
CS2106 Project Assignment 1
This program is written in Go r60.3.
Compiled using the 6g compiler version release.r60.3 9516+ on Darwin
Usage:
./6.out (file mode)
./6.out -t (REPL mode)
*/
// Structs
type Stat struct {
Type string
List *list.List
}
type CT struct {
Parent *PCB
Child *list.List
}
type PCB struct {
PID string
Other_Resources *list.List
Creation_Tree CT
Status Stat
Priority int
}
type RCB struct {
RID string
Status string
Waiting_List *list.List
}
type IO_RCB struct {
Waiting_List *list.List
}
// Global Variables
var (
PIDs = make(map[string]*PCB) // keeps track of all processes
Ready_List = list.New()
Resource_List = list.New()
Curr, Init *PCB // current running process, and init process
IO *IO_RCB
terminal = flag.Bool("t", false, "use terminal mode for input")
output string
)
// Operations on processes
// init for PCB, rarely used
func (p *PCB) Init() *PCB {
p.PID = ""
p.Other_Resources = list.New()
p.Creation_Tree = CT{p, list.New()}
p.Status = Stat{"ready_s", Ready_List}
p.Priority = 0
return p
}
// create new process
// returns os.Error if PID is not unique, or priority is wrong
// returns nil on success
func (p *PCB) Create(name string, priority int) os.Error {
if _, ok := PIDs[name]; ok {
return os.NewError("PID already taken")
}
if priority > 2 {
return os.NewError("No such priority")
}
newP := PCB{name,
list.New(),
CT{p, list.New()},
Stat{"ready_s", Ready_List},
priority}
PIDs[name] = &newP // add to PID name records
p.Creation_Tree.Child.PushFront(&newP)
listRLInsert(&newP)
Scheduler()
return nil
}
// destroy process
func (p *PCB) Destroy(pid string) {
pcb := getPCB(pid)
if pcb != Init {
killTree(pcb)
} else {
fmt.Println("init cannot be destroyed")
output += "init cannot be destroyed\n"
}
Scheduler()
}
// kill creation_tree for given PCB
func killTree(p *PCB) {
c := p.Creation_Tree.Child
children := make([]*PCB, c.Len())
for e := c.Front(); e != nil; e = e.Next() {
children = append(children, e.Value.(*PCB))
}
for _, chld := range children {
if chld != nil {
killTree(chld)
}
}
if p.Status.List == Ready_List {
listRLRemove(p)
} else {
listRemove(p, p.Status.List)
}
// takes care of case where running PCB is deleted
if p.Status.Type == "running" {
Curr = nil
}
parent := p.Creation_Tree.Parent
listRemove(p, parent.Creation_Tree.Child)
// release all resources associated with p
for e := p.Other_Resources.Front(); e != nil; e = e.Next() {
p.release(e.Value.(*RCB).RID)
}
// remove PID and PCB pointer from map 'PIDs'
PIDs[p.PID] = nil, false
}
// request a resource
func (p *PCB) Request(rid string) {
if p == Init {
fmt.Println("init not allowed to request resource")
output += "init not allowed to request resource\n"
return
}
r := getRCB(rid)
if r.Status == "free" {
r.Status = "allocated"
p.Other_Resources.PushBack(r)
} else {
r.Waiting_List.PushBack(p)
listRLRemove(p)
fmt.Printf("Process %s blocked; ", Curr.PID)
output += fmt.Sprintf("Process %s blocked; ", Curr.PID)
p.Status.Type = "blocked_a"
p.Status.List = r.Waiting_List
}
Scheduler()
}
// release a resource
func (p *PCB) Release(rid string) {
p.release(rid)
Scheduler()
}
// release a resource, without call to Scheduler
// for internal use only, e.g.: Destroy
func (p *PCB) release(rid string) {
r := getRCB(rid)
if r.Waiting_List.Len() == 0 {
r.Status = "free"
} else {
pcb := r.Waiting_List.Front().Value.(*PCB)
rcbListRemove(r, pcb.Other_Resources)
r.Waiting_List.Remove(r.Waiting_List.Front()) // remove front
pcb.Status.Type = "ready_a"
pcb.Status.List = Ready_List
listRLInsert(pcb)
}
}
// timeout function
func (p *PCB) Time_out() {
listRLInsert(Curr) // place pointer to Curr running p back into RL
Curr.Status.Type = "ready_a"
Curr = nil
Scheduler()
}
// request IO resource
func (p *PCB) Request_IO() {
p.Status.Type = "blocked_a"
p.Status.List = IO.Waiting_List
listRLRemove(p)
fmt.Printf("Process %s blocked;", p.PID)
output += fmt.Sprintf("Process %s blocked;", p.PID)
iowl := IO.Waiting_List
iowl.PushBack(p)
Scheduler()
}
// IO release
func (p *PCB) IO_completion() {
if IO.Waiting_List.Len() != 0 {
pcb := IO.Waiting_List.Front().Value.(*PCB)
listRemove(pcb, IO.Waiting_List)
pcb.Status.Type = "ready"
pcb.Status.List = Ready_List
listRLInsert(pcb)
Scheduler()
} else {
fmt.Println("No processes on IO")
output += "No processes on IO"
}
}
// calculates which process to run next
// also prints state
func Scheduler() {
p := maxPriorityPCB()
if Curr == nil || Curr.Status.Type != "running" || Curr.Priority < p.Priority {
preempt(p, Curr)
}
fmt.Printf("Process %s is running\n", Curr.PID)
output += fmt.Sprintf("Process %s is running\n", Curr.PID)
}
// preempt function used in scheduler
// replaces Curr running process with p
func preempt(p, prev *PCB) {
if prev != nil {
if prev.Status.Type != "blocked_a" {
prev.Status.Type = "ready_a"
if prev != Init { // edge case, init doesn't need to be re-added to RL
listRLInsert(prev)
}
}
}
Curr = p
p.Status.Type = "running"
listRLRemove(p)
}
// find and return the highest priority PCB
// note that Curr, the current running PCB is not in the RL
func maxPriorityPCB() *PCB {
system := Ready_List.Front()
user := system.Next()
init := user.Next()
switch {
// get top process from priority level 2
case system.Value.(*list.List).Len() != 0:
return system.Value.(*list.List).Front().Value.(*PCB)
// get top process from priority level 1
case user.Value.(*list.List).Len() != 0:
return user.Value.(*list.List).Front().Value.(*PCB)
// get top process from priority level 0
case init.Value.(*list.List).Len() > 1:
return init.Value.(*list.List).Front().Value.(*PCB)
}
return Init // return init
}
// main program
func main() {
flag.Parse()
in := bufio.NewReader(os.Stdin)
// REPL mode
if *terminal {
initialize()
for {
i, err := in.ReadString('\n')
if err != nil {
fmt.Println("Read error:", err)
}
i = strings.TrimSpace(i)
if i == "quit" && len(strings.Split(i, " ")) == 1 {
fmt.Println("process terminated")
break
}
Manager(i)
}
// File mode
} else {
// get the file path
fmt.Println("Give me a file path:")
filepath, _ := in.ReadString('\n')
filepath = strings.TrimSpace(filepath)
// open the file
file, err := os.Open(filepath)
if err != nil {
fmt.Println("File open error:", err)
panic(err)
}
// declare a new file reader
reader := bufio.NewReader(file)
// load each command into a slice named lines
var lines []string
for {
tmp, error := reader.ReadString('\n')
if error == nil {
tmp = strings.TrimSpace(tmp)
lines = append(lines, tmp)
}
// end of file, break
if error == os.EOF {
break
}
if error != nil {
fmt.Println("Readline error:", error)
panic(error)
}
}
// initialize the kernel environment
initialize()
// for each command, process it
for _, v := range lines {
Manager(v)
}
dirpath, _ := path.Split(filepath)
fl, flErr := os.OpenFile(path.Join(dirpath, "U096996N.txt"), os.O_RDWR|os.O_CREATE, 0666)
if flErr != nil {
fmt.Println("File write error:", flErr)
}
defer fl.Close()
// for each output, write it
_, wErr := io.WriteString(fl, output) // write
if wErr != nil {
fmt.Println("Write error:", wErr)
}
}
}
// Helper functions
// set up all the structs needed for the program to run
func initialize() {
fmt.Print("init")
output += "init"
// clear the global lists
Ready_List.Init()
Resource_List.Init()
IO = &IO_RCB{list.New()}
PIDs = make(map[string]*PCB)
Init = &PCB{
"init",
list.New(),
CT{nil, list.New()},
Stat{"ready_s", Ready_List},
0}
Curr = Init
PIDs["init"] = Init
Ready_List.PushFront(list.New())
Ready_List.PushFront(list.New())
Ready_List.PushFront(list.New())
listRLInsert(Init)
Resource_List.PushFront(&RCB{"R1", "free", list.New()})
Resource_List.PushFront(&RCB{"R2", "free", list.New()})
Resource_List.PushFront(&RCB{"R3", "free", list.New()})
Resource_List.PushFront(&RCB{"R4", "free", list.New()})
fmt.Println(" ... done\nProcess init is running")
output += " ... done\n\nProcess init is running\n"
}
// handles commands and dispatches the appropirate operations
func Manager(cmd string) {
cmds := strings.Split(cmd, " ")
switch ins := cmds[0]; {
case ins == "cr" && len(cmds) == 3:
x, _ := strconv.Atoi(cmds[2])
err := Curr.Create(cmds[1], x)
if err != nil {
fmt.Println(err)
}
case ins == "de" && len(cmds) == 2:
Curr.Destroy(cmds[1])
case ins == "req" && len(cmds) == 2:
Curr.Request(cmds[1])
case ins == "rel" && len(cmds) == 2:
Curr.Release(cmds[1])
case ins == "to" && len(cmds) == 1:
Curr.Time_out()
case ins == "init" && len(cmds) == 1:
initialize()
case ins == "rio" && len(cmds) == 1:
Curr.Request_IO()
case ins == "ioc" && len(cmds) == 1:
Curr.IO_completion()
case ins == "" && len(cmds) == 1:
fmt.Println("")
case ins == "quit" && len(cmds) == 1:
fmt.Println("Process terminated")
output += "Process terminated\n"
break
default:
fmt.Println("Unknown command")
}
}
// calculates where to place processes on the RL
func listRLInsert(p *PCB) {
pr := p.Priority
var e *list.Element
switch {
case pr == 2:
e = Ready_List.Front()
case pr == 1:
e = Ready_List.Front().Next()
case pr == 0:
e = Ready_List.Front().Next().Next()
}
ls := e.Value.(*list.List)
ls.PushBack(p)
}
// removes process from the RL
func listRLRemove(p *PCB) {
pr := p.Priority
var e *list.Element
switch {
case pr == 2:
e = Ready_List.Front()
case pr == 1:
e = Ready_List.Front().Next()
case pr == 0:
e = Ready_List.Front().Next().Next()
}
ls := e.Value.(*list.List)
listRemove(p, ls)
}
// removes PCB element from a linked list
func listRemove(p *PCB, ls *list.List) {
for e := ls.Front(); e != nil; e = e.Next() {
if e.Value.(*PCB).PID == p.PID {
ls.Remove(e)
}
}
}
// removes RCB element from a linked list
func rcbListRemove(r *RCB, ls *list.List) {
for e := ls.Front(); e != nil; e = e.Next() {
if e.Value.(*RCB).RID == r.RID {
ls.Remove(e)
}
}
}
// returns PCB item given PID
func getPCB(name string) *PCB {
if res, ok := PIDs[name]; ok {
return res
}
return nil
}
// returns RCB item given RID
func getRCB(rid string) *RCB {
for e := Resource_List.Front(); e != nil; e = e.Next() {
if e.Value.(*RCB).RID == rid {
return e.Value.(*RCB)
}
}
return nil
}