If I have the PID of a process, is os.FindProcess enough to test for the existing of the process? I mean if it returns err can I assume that it's terminated (or killed)?

Edit:

I've just wrote a wrapper function around kill -s 0 (old-style bash process testing). This works without any problem, but I'm still happy if there is other solutions (done with go libraries) to this problem.:

func checkPid(pid int) bool {
    out, err := exec.Command("kill", "-s", "0", strconv.Itoa(pid)).CombinedOutput()
    if err != nil {
        log.Println(err)
    }

    if string(out) == "" {
        return true // pid exist
    }
    return false
}
share|improve this question
up vote 26 down vote accepted

Here is the traditional unix way to see if a process is alive - send it a signal of 0 (like you did with your bash example).

From kill(2):

   If  sig  is 0, then no signal is sent, but error checking is still per‐
   formed; this can be used to check for the existence of a process ID  or
   process group ID.

And translated into Go

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)
        }

    }
}

When you run it you get this, showing that process 123 is dead, process 1 is alive but not owned by you and process 12606 is alive and owned by you.

$ ./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
share|improve this answer
    
Thats it! Thanks for showing the Go way :) – Fatih Arslan Mar 4 '13 at 20:39
    
Why are you parsing into int64. Wouldn't Atoi be better (no type converting in FindProcess)? – tjameson Mar 9 '13 at 11:59
    
Yes you are right Atoi would be better. I guess I used ParseInt more recently and forgot about it! – Nick Craig-Wood Mar 9 '13 at 15:40
    
Meanwhile, this has no effect on process wich has became zombie and not harvested by parent – frostyplanet Jun 11 '17 at 5:23

On unix like systems (linux, freebsd, etc) os.FindProcess will never return an error. I don't know what happens on Windows. This means you won't know if the PID is correct until you try to use the *os.Process for something.

You can look at the code here.

share|improve this answer
    
You're right. It always gives true, I've found work-around (look my edit above) – Fatih Arslan Mar 4 '13 at 17:00
    
From my experience on Windows 10, os.FindProcess returns error if process with given PID is not running. – Kerrmiter Jun 2 '17 at 15:39

You can also just use syscall.Kill. It amounts to less code.

killErr := syscall.Kill(pid, syscall.Signal(0))
procExists := killErr == nil
share|improve this answer
    
Except note from Nick Craig-Wood's answer that a non-nil error can be returned for existing processes. You should have a more involved conditional (perhaps err == nil || err == syscall.EPERM, perhaps more). – Dave C Sep 19 '15 at 16:15

If a previously known pid is not found in the system (not sure of go functions), it means process has definitely terminated and has been joined (on Unix, with wait call) too.

But other way around is not necessarily true. Just because a pid exists, it does not quarantee it is same process as before. There are only 65535 valid pids in standard Linux for example, and they can get re-used when there is a wrap-around. However, if you check reasonably often, for practical purposes you don't need to care about this (as long as pid of wrong new process being found is not a security vulnerability or something else critical, which somebody might try to trigger intentionally for malicious purposes).

Related links (and Related questions on their right columns):

share|improve this answer
    
I wish I could upvote more than once. The observation that pids are reused is critical for anyone wishing to reliably monitor processes on modern hardware: if something is misbehaving and being respawned, the pid namespace will be exhausted quickly. Since thread id's are in the same namespace as process id's, heavily threaded processes exacerbate the problem. – Mark Jul 11 '16 at 1:53
1  
Forgot to mention... If you need additional confidence, verify that the process start time for $pid hasn't changed between checks. If it has, it's a different process. If not, it's highly unlikely to be a different process. – Mark Jul 11 '16 at 2:06
    
What do you mean by "highly unlikely"? Under what circumstances could it not be a different process? Assuming that the process has been alive longer than one unit of whatever it's start time is measured in (so a quick die/recreate with PID wraparound didn't confuse the checker), the only circumstance I can think of is start-time wraparound. Are there others? – Zac B Dec 23 '16 at 21:23

On Windows checking the result of os.FindProcess() seems to be enough to check if process is running.

func isProcessRunning(pid int) bool {
    _, err = os.FindProcess(pid)
    if err != nil {
        return false
    }
    if runtime.GOOS == "windows" {
        return true
    }
    return false // further checking for other systems then Windows is not supported here
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.