PidsOf returns pid(s) of a process by name
(name string)
| 705 | |
| 706 | // PidsOf returns pid(s) of a process by name |
| 707 | func PidsOf(name string) ([]int, error) { |
| 708 | if len(name) == 0 { |
| 709 | return []int{}, fmt.Errorf("name is required") |
| 710 | } |
| 711 | |
| 712 | procDirFD, err := os.Open("/proc") |
| 713 | if err != nil { |
| 714 | return nil, fmt.Errorf("failed to open /proc: %w", err) |
| 715 | } |
| 716 | defer procDirFD.Close() |
| 717 | |
| 718 | res := []int{} |
| 719 | for { |
| 720 | fileInfos, err := procDirFD.Readdir(100) |
| 721 | if err != nil { |
| 722 | if err == io.EOF { |
| 723 | break |
| 724 | } |
| 725 | return nil, fmt.Errorf("failed to readdir: %w", err) |
| 726 | } |
| 727 | |
| 728 | for _, fileInfo := range fileInfos { |
| 729 | if !fileInfo.IsDir() { |
| 730 | continue |
| 731 | } |
| 732 | |
| 733 | pid, err := strconv.Atoi(fileInfo.Name()) |
| 734 | if err != nil { |
| 735 | continue |
| 736 | } |
| 737 | |
| 738 | exePath, err := os.Readlink(filepath.Join("/proc", fileInfo.Name(), "exe")) |
| 739 | if err != nil { |
| 740 | continue |
| 741 | } |
| 742 | |
| 743 | if strings.HasSuffix(exePath, name) { |
| 744 | res = append(res, pid) |
| 745 | } |
| 746 | } |
| 747 | } |
| 748 | return res, nil |
| 749 | } |
| 750 | |
| 751 | // PidEnvs returns the environ of pid in key-value pairs. |
| 752 | func PidEnvs(pid int) (map[string]string, error) { |
no test coverage detected
searching dependent graphs…