Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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.

like image 855
developomp Avatar asked Oct 15 '25 01:10

developomp


1 Answers

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.

like image 183
Marc Avatar answered Oct 17 '25 22:10

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!