github.com/toplink-cn/moby@v0.0.0-20240305205811-460b4aebdf81/pkg/reexec/reexec.go (about)

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