'How to check if a Go program isn't running via the go run command?

I want to know if there is a non OS-specific way to test if a Go program is launched by using the go run command or by executing the binary produced by the go build command.

go


Solution 1:[1]

First: it's always compiled.

Second: There is no guaranteed way to tell the difference between binaries compiled using go build and go run.

go run main.go just builds a temporary binary and executes it.

You can look at the path of the binary being executed by printing os.Args[0] (the first argument). eg for the following program:

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println(os.Args[0])
}
$ go run main.go
/tmp/go-build854217312/b001/exe/main

$  go build -o main . && ./main
./main

You could try to detect the fact that the first one is in a temporary directory but the location will depend on the OS and is not guaranteed to remain the same across go versions.

Overall, it might not be worth it. go run is not acceptable for any serious binary, it should always be compiled.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1