From 7cf8e470471d30fc821a8be350dcb97dc64e5add Mon Sep 17 00:00:00 2001 From: We-unite <3205135446@qq.com> Date: Fri, 19 Jul 2024 17:02:11 +0800 Subject: Depart the whole program into several files. Put all the src code in only one file is to ugly, so devide it! and mv them into src dir to keep the whole repo clear. --- src/basefunc.go | 115 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 src/basefunc.go (limited to 'src/basefunc.go') diff --git a/src/basefunc.go b/src/basefunc.go new file mode 100644 index 0000000..5fff3e8 --- /dev/null +++ b/src/basefunc.go @@ -0,0 +1,115 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" +) + +func figureOutSyscalls() error { + NRRegex := regexp.MustCompile(`#define __NR_(.*?) (\d+)$`) + file, err := os.Open("/usr/include/asm/unistd_64.h") + if err != nil { + return err + } + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := scanner.Text() + if NRRegex.MatchString(line) { + match := NRRegex.FindStringSubmatch(line) + num, err := strconv.Atoi(match[2]) + if err != nil { + return err + } + syscallTable[num] = match[1] + } + } + return nil +} + +func getPid() (int, error) { + // 指定要搜索的关键词 + keyword := "/usr/bin/containerd" + + // 获取/proc目录下的所有子目录 + procDir, err := filepath.Glob("/proc/*") + if err != nil { + return 0, err + } + + // 遍历子目录,查找包含关键词的进程 + for _, dir := range procDir { + pid, err := strconv.Atoi(filepath.Base(dir)) + if err != nil { + continue // 跳过非PID的目录 + } + + // 检查进程是否包含关键词 + if containsKeyword(pid, keyword) { + return pid, nil + } + } + err = fmt.Errorf("Error: no containerd process found.") + return 0, err +} + +func containsKeyword(pid int, keyword string) bool { + // 构造完整的进程命令路径 + cmdPath := fmt.Sprintf("/proc/%d/cmdline", pid) + + // 打开文件 + file, err := os.Open(cmdPath) + if err != nil { + return false + } + defer file.Close() + + // 读取文件内容 + scanner := bufio.NewScanner(file) + scanner.Split(bufio.ScanLines) + for scanner.Scan() { + line := scanner.Text() + if strings.Contains(line, keyword) { + return true + } + } + return false +} + +func getTimeFromStr(timeStr string) (time.Time, error) { + timestampFloat, err := strconv.ParseFloat(timeStr, 64) + if err != nil { + return time.Unix(0, 0), err + } + secs := int64(timestampFloat) + nsecs := int64((timestampFloat - float64(secs)) * 1e9) + + // 只精确到毫秒就够了 + t := time.Unix(secs, nsecs).Truncate(time.Millisecond) + return t, nil +} + +func hexToAscii(hexString string) string { + bytes := []byte{} + for i := 0; i < len(hexString); i += 2 { + hexPair := hexString[i : i+2] + // 将十六进制数转换为十进制数 + decimal, err := strconv.ParseInt(hexPair, 16, 8) + if err != nil { + return "Invalid hex string" + } + char := byte(decimal) + bytes = append(bytes, char) + } + + asciiString := strings.ReplaceAll(string(bytes), "\000", " ") + + return asciiString +} -- cgit v1.2.3-70-g09d2