github.com/iDigitalFlame/xmt@v0.5.4/cmd/y_linux_no_crypt.go (about)

     1  //go:build !windows && !js && !crypt
     2  // +build !windows,!js,!crypt
     3  
     4  // Copyright (C) 2020 - 2023 iDigitalFlame
     5  //
     6  // This program is free software: you can redistribute it and/or modify
     7  // it under the terms of the GNU General Public License as published by
     8  // the Free Software Foundation, either version 3 of the License, or
     9  // any later version.
    10  //
    11  // This program is distributed in the hope that it will be useful,
    12  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  // GNU General Public License for more details.
    15  //
    16  // You should have received a copy of the GNU General Public License
    17  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    18  //
    19  
    20  package cmd
    21  
    22  import (
    23  	"os"
    24  	"sort"
    25  	"strconv"
    26  )
    27  
    28  // Processes attempts to gather the current running Processes and returns them
    29  // as a slice of ProcessInfo structs, otherwise any errors are returned.
    30  func Processes() ([]ProcessInfo, error) {
    31  	f, err := os.OpenFile("/proc/", 0, 0)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	l, err := f.Readdir(0)
    36  	if f.Close(); err != nil {
    37  		return nil, err
    38  	}
    39  	if len(l) == 0 {
    40  		return nil, nil
    41  	}
    42  	var (
    43  		v uint64
    44  		p uint32
    45  		n string
    46  		r = make(processList, 0, len(l)/2)
    47  	)
    48  	for i := range l {
    49  		if !l[i].IsDir() {
    50  			continue
    51  		}
    52  		if n = l[i].Name(); len(n) < 1 || n[0] < 48 || n[0] > 57 {
    53  			continue
    54  		}
    55  		if v, err = strconv.ParseUint(n, 10, 32); err != nil {
    56  			continue
    57  		}
    58  		if n, p = readProcStats("/proc/" + n + "/status"); len(n) == 0 {
    59  			continue
    60  		}
    61  		r = append(r, ProcessInfo{Name: n, User: getProcUser("/proc/" + n), PID: uint32(v), PPID: p})
    62  	}
    63  	sort.Sort(r)
    64  	return r, nil
    65  }