Home >Backend Development >Golang >Does a Failed os.FindProcess Call in Go Necessarily Mean a Process Has Terminated?
Determining Process Existence in Go
In Go, the os.FindProcess function can be used to retrieve a process by its PID. However, if this function returns an error, does it necessarily indicate that the process has terminated?
Checking for Process Existence
According to the man page for kill(2) in Unix, sending a signal of 0 to a process does not actually send a signal but checks if the process is alive. This approach can be adapted in Go to determine the existence of a process.
Go Implementation
The following Go code demonstrates this technique:
package main import ( "fmt" "log" "os" "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) } } }
Sample Output
When run, this code will display the status of multiple processes:
$ ./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
In this example, process 1 returns an error because it is not owned by the current user. Process 12606 returns nil because it is alive and owned by the user. Process 123 returns an error because it no longer exists.
The above is the detailed content of Does a Failed os.FindProcess Call in Go Necessarily Mean a Process Has Terminated?. For more information, please follow other related articles on the PHP Chinese website!