2014-08-08 16:18:18 -04:00
|
|
|
package reexec
|
|
|
|
|
2014-08-11 21:13:27 -04:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2014-08-12 17:57:09 -04:00
|
|
|
"os/exec"
|
|
|
|
"path/filepath"
|
2014-08-11 21:13:27 -04:00
|
|
|
)
|
2014-08-08 16:18:18 -04:00
|
|
|
|
|
|
|
var registeredInitializers = make(map[string]func())
|
|
|
|
|
|
|
|
// Register adds an initialization func under the specified name
|
|
|
|
func Register(name string, initializer func()) {
|
2014-08-11 21:13:27 -04:00
|
|
|
if _, exists := registeredInitializers[name]; exists {
|
|
|
|
panic(fmt.Sprintf("reexec func already registred under name %q", name))
|
|
|
|
}
|
|
|
|
|
2014-08-08 16:18:18 -04:00
|
|
|
registeredInitializers[name] = initializer
|
|
|
|
}
|
|
|
|
|
|
|
|
// Init is called as the first part of the exec process and returns true if an
|
|
|
|
// initialization function was called.
|
|
|
|
func Init() bool {
|
|
|
|
initializer, exists := registeredInitializers[os.Args[0]]
|
|
|
|
if exists {
|
|
|
|
initializer()
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2014-08-12 17:57:09 -04:00
|
|
|
|
|
|
|
// Self returns the path to the current processes binary
|
|
|
|
func Self() string {
|
|
|
|
name := os.Args[0]
|
|
|
|
if filepath.Base(name) == name {
|
|
|
|
if lp, err := exec.LookPath(name); err == nil {
|
|
|
|
name = lp
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return name
|
|
|
|
}
|