summaryrefslogtreecommitdiffstats
path: root/src/deal.go
blob: fd9f7887e28b1d0c9b4deca3b0b44ae41bede2a4 (plain) (blame)
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
package main

import (
	"fmt"
	"time"
)

func deal() {
	defer wg.Done()
	var cooked Event
	var ok bool
	for {
		cooked, ok = <-cookedChan
		if !ok {
			break
		}
		// type Event struct {
		// 	timestamp time.Time
		// 	pid, ppid int
		// 	syscall   int
		// 	argc      int
		// 	args      []string
		// 	cwd       string
		// }
		// type process struct {
		// 	timestamp time.Time
		// 	pid, ppid int
		// 	argv      []string
		// 	cwd       string
		// 	rootfs    string
		// 	children  []int
		// }
		switch syscallTable[cooked.syscall] {
		case "fork", "vfork", "clone":
			ppid := cooked.ppid
			pid := cooked.pid
			parent, ok := pids.Load(ppid)
			if !ok {
				break
			}
			parent.(*process).children = append(parent.(*process).children, pid)
			pids.Store(pid, &process{
				timestamp: cooked.timestamp,
				pid:       cooked.pid,
				ppid:      cooked.ppid,
				argv:      cooked.argv,
				cwd:       cooked.cwd,
				children:  make([]int, 0),
			})
			fmt.Printf("%v syscall=%d, ppid=%d, pid=%d, cwd=\"%s\", argc=%d, ", cooked.timestamp, cooked.syscall, cooked.ppid, cooked.pid, cooked.cwd, cooked.argc)
			for i := 0; i < cooked.argc; i++ {
				fmt.Printf("arg[%d]=\"%s\", ", i, cooked.argv[i])
			}
			fmt.Printf("\n")
		case "exit", "exit_group":
			_, ok := pids.Load(cooked.pid)
			if !ok {
				break
			}
			go deletePid(cooked)
		}
	}
}

func deletePid(cooked Event) {
	time.Sleep(1 * time.Second)
	Process, ok := pids.Load(cooked.pid)
	if !ok {
		return
	}
	pProcess := Process.(*process)

	// 先从爹那里注销户籍
	parent, ok := pids.Load(pProcess.ppid)
	if ok {
		pParent := parent.(*process)
		for i, child := range pParent.children {
			if child == pProcess.pid {
				pParent.children = append(pParent.children[:i], pParent.children[i+1:]...)
				break
			}
		}
	}

	// 子进程需要收容
	for i := 0; i < len(pProcess.children); i++ {
		child, ok := pids.Load(pProcess.children[i])
		if ok {
			child.(*process).ppid = 1
		}
	}

	// 可以去死了
	pids.Delete(cooked.pid)
	_, ok = pids.Load(cooked.pid)
	fmt.Printf("%v Goodbye, %d! ok = %v\n", time.Now(), cooked.pid, ok)
}