pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/pid/pid_linux.go (about)

     1  package pid
     2  
     3  // ////////////////////////////////////////////////////////////////////////////////// //
     4  //                                                                                    //
     5  //                         Copyright (c) 2022 ESSENTIAL KAOS                          //
     6  //      Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>     //
     7  //                                                                                    //
     8  // ////////////////////////////////////////////////////////////////////////////////// //
     9  
    10  import (
    11  	"fmt"
    12  	"os"
    13  	"syscall"
    14  
    15  	"pkg.re/essentialkaos/ek.v12/fsutil"
    16  )
    17  
    18  // ////////////////////////////////////////////////////////////////////////////////// //
    19  
    20  // procfsDir is path to procfs directory
    21  var procfsDir = "/proc"
    22  
    23  // ////////////////////////////////////////////////////////////////////////////////// //
    24  
    25  // IsWorks returns true if process with PID from PID file is works
    26  func IsWorks(name string) bool {
    27  	pid := Get(name)
    28  
    29  	if pid == -1 {
    30  		return false
    31  	}
    32  
    33  	if !fsutil.IsExist(fmt.Sprintf("%s/%d", procfsDir, pid)) {
    34  		return false
    35  	}
    36  
    37  	_, _, initCDate, _ := fsutil.GetTimestamps(fmt.Sprintf("%s/%d", procfsDir, 1))
    38  	_, _, procCDate, _ := fsutil.GetTimestamps(fmt.Sprintf("%s/%d", procfsDir, pid))
    39  
    40  	if initCDate != -1 && procCDate != -1 && initCDate > procCDate {
    41  		return false
    42  	}
    43  
    44  	return IsProcessWorks(pid)
    45  }
    46  
    47  // IsProcessWorks returns true if process with given PID is works
    48  func IsProcessWorks(pid int) bool {
    49  	// On Unix systems, FindProcess always succeeds and returns a Process
    50  	// for the given pid, regardless of whether the process exists.
    51  	pr, _ := os.FindProcess(pid)
    52  	return pr.Signal(syscall.Signal(0)) == nil
    53  }