|
| 1 | +package reexec_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/moby/sys/reexec" |
| 8 | +) |
| 9 | + |
| 10 | +func init() { |
| 11 | + reexec.Register("example-foo", func() { |
| 12 | + fmt.Println("Hello from entrypoint example-foo") |
| 13 | + }) |
| 14 | + reexec.Register("example-bar", func() { |
| 15 | + fmt.Println("Hello from entrypoint example-bar") |
| 16 | + }) |
| 17 | +} |
| 18 | + |
| 19 | +// Example_multicall demonstrates a BusyBox-style multi-call binary. |
| 20 | +// |
| 21 | +// In a real multi-call binary: |
| 22 | +// |
| 23 | +// go build -o example . |
| 24 | +// ln -s example example-foo |
| 25 | +// ln -s example example-bar |
| 26 | +// |
| 27 | +// ./example-foo # runs entrypoint "example-foo" |
| 28 | +// ./example-bar # runs entrypoint "example-bar" |
| 29 | +// |
| 30 | +// At process startup, main would call [reexec.Init] and return if it |
| 31 | +// matches an entrypoint. This example first shows that call, then emulates |
| 32 | +// different invocation names by modifying os.Args[0]. |
| 33 | +func Example_multicall() { |
| 34 | + // What main would normally do: |
| 35 | + if reexec.Init() { |
| 36 | + // Matched a reexec entrypoint; stop normal main execution. |
| 37 | + return |
| 38 | + } |
| 39 | + reset := os.Args[0] |
| 40 | + |
| 41 | + // Emulate running as "example-foo". |
| 42 | + os.Args[0] = "example-foo" |
| 43 | + _ = reexec.Init() |
| 44 | + |
| 45 | + // Emulate running as "example-bar". |
| 46 | + os.Args[0] = "example-bar" |
| 47 | + _ = reexec.Init() |
| 48 | + |
| 49 | + // Emulate running under the default binary name (no match). |
| 50 | + os.Args[0] = reset |
| 51 | + if !reexec.Init() { |
| 52 | + fmt.Println("Hello main") |
| 53 | + } |
| 54 | + |
| 55 | + // Output: |
| 56 | + // Hello from entrypoint example-foo |
| 57 | + // Hello from entrypoint example-bar |
| 58 | + // Hello main |
| 59 | +} |
0 commit comments