github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/pkg/reexec/reexec.go (about)

     1  package reexec // import "github.com/demonoid81/moby/pkg/reexec"
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"path/filepath"
     8  )
     9  
    10  var registeredInitializers = make(map[string]func())
    11  
    12  // Register adds an initialization func under the specified name
    13  func Register(name string, initializer func()) {
    14  	if _, exists := registeredInitializers[name]; exists {
    15  		panic(fmt.Sprintf("reexec func already registered under name %q", name))
    16  	}
    17  
    18  	registeredInitializers[name] = initializer
    19  }
    20  
    21  // Init is called as the first part of the exec process and returns true if an
    22  // initialization function was called.
    23  func Init() bool {
    24  	initializer, exists := registeredInitializers[os.Args[0]]
    25  	if exists {
    26  		initializer()
    27  
    28  		return true
    29  	}
    30  	return false
    31  }
    32  
    33  func naiveSelf() string {
    34  	name := os.Args[0]
    35  	if filepath.Base(name) == name {
    36  		if lp, err := exec.LookPath(name); err == nil {
    37  			return lp
    38  		}
    39  	}
    40  	// handle conversion of relative paths to absolute
    41  	if absName, err := filepath.Abs(name); err == nil {
    42  		return absName
    43  	}
    44  	// if we couldn't get absolute name, return original
    45  	// (NOTE: Go only errors on Abs() if os.Getwd fails)
    46  	return name
    47  }