Is There a Reliable Way to Determine Process Existence in Go?

Barbara Streisand
Release: 2024-11-06 22:34:02
Original
974 people have browsed it

Is There a Reliable Way to Determine Process Existence in Go?

Determining Process Existence in Go using os.FindProcess

While using os.FindProcess can provide information about a process's existence, it's not entirely reliable for determining if a process has been terminated or killed.

Leveraging the Unix Approach

Traditionally, the Unix command kill -s 0 [PID] is employed to check if a process is still running. This approach sends a signal of 0 to the process, with no actual signal being sent. Instead, it serves as a way to verify the process's existence.

Implementation in Go

Translating this method into Go, the following code demonstrates how to determine if a process is still active:

import (
    "fmt"
    "log"
    "os"
    "os/exec"
    "strconv"
    "syscall"
)

func main() {
    for _, p := range os.Args[1:] {
        pid, err := strconv.ParseInt(p, 10, 64)
        if err != nil {
            log.Fatal(err)
        }
        process, err := os.FindProcess(int(pid))
        if err != nil {
            fmt.Printf("Failed to find process: %s\n", err)
        } else {
            err := process.Signal(syscall.Signal(0))
            fmt.Printf("process.Signal on pid %d returned: %v\n", pid, err)
        }
    }
}
Copy after login

Example Output

Running this code provides the following output, indicating the status of processes with different IDs:

$ ./kill 1 $$ 123
process.Signal on pid 1 returned: operation not permitted
process.Signal on pid 12606 returned: <nil>
process.Signal on pid 123 returned: no such process
Copy after login
  • Process 1: Alive but not owned by the current user.
  • Process 12606: Alive and owned by the current user.
  • Process 123: Terminated or killed.

The above is the detailed content of Is There a Reliable Way to Determine Process Existence in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!