"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Does a Failed os.FindProcess Call in Go Necessarily Mean a Process Has Terminated?

Does a Failed os.FindProcess Call in Go Necessarily Mean a Process Has Terminated?

Published on 2024-11-14
Browse:436

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: 
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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3