本文整理匯總了Golang中syscall.Exec函數的典型用法代碼示例。如果您正苦於以下問題:Golang Exec函數的具體用法?Golang Exec怎麽用?Golang Exec使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Exec函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: unshareAndBind
func unshareAndBind(workingRootDir string) bool {
if *unshare {
// Re-exec myself using the unshare syscall while on a locked thread.
// This hack is required because syscall.Unshare() operates on only one
// thread in the process, and Go switches execution between threads
// randomly. Thus, the namespace can be suddenly switched for running
// code. This is an aspect of Go that was not well thought out.
runtime.LockOSThread()
err := syscall.Unshare(syscall.CLONE_NEWNS)
if err != nil {
fmt.Printf("Unable to unshare mount namesace\t%s\n", err)
return false
}
args := append(os.Args, "-unshare=false")
err = syscall.Exec(args[0], args, os.Environ())
if err != nil {
fmt.Printf("Unable to Exec:%s\t%s\n", args[0], err)
return false
}
}
err := syscall.Mount("none", "/", "", syscall.MS_REC|syscall.MS_PRIVATE, "")
if err != nil {
fmt.Printf("Unable to set mount sharing to private\t%s\n", err)
return false
}
syscall.Unmount(workingRootDir, 0)
err = syscall.Mount(*rootDir, workingRootDir, "", syscall.MS_BIND, "")
if err != nil {
fmt.Printf("Unable to bind mount %s to %s\t%s\n",
*rootDir, workingRootDir, err)
return false
}
return true
}
示例2: startAttachTag
func startAttachTag(tag string) {
if *dockerFlag == "" {
*dockerFlag, _ = exec.LookPath("docker")
}
var containers []string
img := "gc14:" + tag
foreachDockerPs(func(runningImage, containerID string) {
if runningImage != img {
return
}
containers = append(containers, containerID)
})
switch {
case len(containers) > 1:
for _, container := range containers {
// Best effort:
exec.Command(*dockerFlag, "kill", container).Run()
exec.Command(*dockerFlag, "rm", container).Run()
}
case len(containers) == 1:
if err := syscall.Exec(*dockerFlag,
[]string{*dockerFlag, "attach", containers[0]},
os.Environ()); err != nil {
log.Fatalf("docker attach exec: %v", err)
}
}
if err := syscall.Exec(*dockerFlag,
[]string{*dockerFlag, "run", "-t", "-i", "-h", tag, "-w", "/home/gopher", img, "/bin/bash"},
os.Environ()); err != nil {
log.Fatalf("docker run exec: %v", err)
}
}
示例3: ExecAsUser
func (UserExecer) ExecAsUser(uid, gid int, workDir, programName string, args ...string) error {
if _, _, errNo := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0); errNo != 0 {
return fmt.Errorf("system: setgid: %s", errNo.Error())
}
if _, _, errNo := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0); errNo != 0 {
return fmt.Errorf("system: setuid: %s", errNo.Error())
}
if workDir == "" {
return errors.New("system: working directory is not provided.")
}
if err := os.MkdirAll(workDir, 0755); err != nil {
return fmt.Errorf("system: %s", err)
}
if err := os.Chdir(workDir); err != nil {
return fmt.Errorf("system: invalid working directory: %s", workDir)
}
programPath, err := exec.LookPath(programName)
if err != nil {
return fmt.Errorf("system: program '%s' was not found in $PATH: %s", programName, err)
}
if err := syscall.Exec(programPath, append([]string{programName}, args...), os.Environ()); err != nil {
return fmt.Errorf("system: exec of %s: %s", programName, err)
}
return nil
}
示例4: executeProgram
func executeProgram(args *DockerInitArgs) error {
setupEnv(args)
if err := setupNetworking(args); err != nil {
return err
}
if err := setupCapabilities(args); err != nil {
return err
}
if err := setupWorkingDirectory(args); err != nil {
return err
}
if err := changeUser(args); err != nil {
return err
}
path, err := exec.LookPath(args.args[0])
if err != nil {
log.Printf("Unable to locate %v", args.args[0])
os.Exit(127)
}
if err := syscall.Exec(path, args.args, os.Environ()); err != nil {
panic(err)
}
// Will never reach here
return nil
}
示例5: main
func main() {
// Para nuestro ejemplo usaremos `ls`. Go necesita
// la ruta absoluta al binario que queremos ejecutar,
// así que usaremos `exec.LookPath` para encontrarla
// (probablemente está en `/bin/ls`).
binary, lookErr := exec.LookPath("ls")
if lookErr != nil {
panic(lookErr)
}
// `Exec` necesita los argumentos en forma de slice
// (en vez de un solo string). Le daremos a `ls`
// algunos argumentos comunes. El primer argumento
// debe de ser el nombre del programa.
args := []string{"ls", "-a", "-l", "-h"}
// `Exec` también necesita un conjunto de [variables de entorno](variables-de-entorno).
// Aquí solamente le pasaremos nuestro ambiente
// actual.
env := os.Environ()
// Aquí está la llamada a `os.Exec`. Si la llamada
// es exitósa, la ejecución de nuestro proceso
// terminará y será reemplazada por el proceso
// `/bin/ls -a -l -h`. Si existe algún error,
// recibiremos un valor de retorno.
execErr := syscall.Exec(binary, args, env)
if execErr != nil {
panic(execErr)
}
}
示例6: Run
// Run implements the running part of 'plz run'.
func Run(graph *core.BuildGraph, label core.BuildLabel, args []string) {
target := graph.TargetOrDie(label)
if !target.IsBinary {
log.Fatalf("Target %s cannot be run; it's not marked as binary", label)
}
// ReplaceSequences always quotes stuff in case it contains spaces or special characters,
// that works fine if we interpret it as a shell but not to pass it as an argument here.
cmd := strings.Trim(build.ReplaceSequences(target, fmt.Sprintf("$(out_exe %s)", target.Label)), "\"")
// Handle targets where $(exe ...) returns something nontrivial
splitCmd := strings.Split(cmd, " ")
if !strings.Contains(splitCmd[0], "/") {
// Probably it's a java -jar, we need an absolute path to it.
cmd, err := exec.LookPath(splitCmd[0])
if err != nil {
log.Fatalf("Can't find binary %s", splitCmd[0])
}
splitCmd[0] = cmd
}
args = append(splitCmd, args...)
log.Info("Running target %s...", strings.Join(args, " "))
output.SetWindowTitle("plz run: " + strings.Join(args, " "))
if err := syscall.Exec(splitCmd[0], args, os.Environ()); err != nil {
log.Fatalf("Error running command %s: %s", strings.Join(args, " "), err)
}
}
示例7: execDocker
func execDocker(config *Config, docker, cmd string, args []string) (*exec.Cmd, error) {
if len(args) > 0 && args[0] == "docker" {
args = args[1:]
}
log.Debugf("Launching Docker %s %s %v", docker, cmd, args)
env := os.Environ()
if len(config.Environment) != 0 {
env = append(env, config.Environment...)
}
if config.Fork {
cmd := exec.Command(docker, args...)
if !config.NoLog {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
cmd.Env = env
err := cmd.Start()
return cmd, err
} else {
err := syscall.Exec(expand(docker), append([]string{cmd}, args...), env)
return nil, err
}
}
示例8: execBootstrap
func execBootstrap() error {
command := []string{}
if len(os.Args) == 2 {
command = []string{"/bin/bash"}
} else {
if len(os.Args) == 3 && strings.Contains(os.Args[2], " ") {
command = []string{"/bin/bash", "-c", os.Args[2]}
} else {
command = os.Args[2:]
}
}
ioutil.WriteFile(os.Args[1], []byte{}, 0)
ioutil.ReadFile(os.Args[1])
err := os.Remove(os.Args[1])
if err != nil {
return fmt.Errorf(
"can't remove control file '%s': %s", os.Args[1], err,
)
}
err = syscall.Exec(command[0], command[0:], os.Environ())
if err != nil {
return fmt.Errorf(
"can't execute bootstrapped command %q: %s", os.Args, err,
)
}
return nil
}
示例9: RestartProcess
// RestartProcess returns an error if things couldn't be
// restarted. On success, this function never returns
// because the process becomes the new process.
func RestartProcess() error {
path, err := SelfPath()
if err != nil {
return fmt.Errorf("RestartProcess failed: %v", err)
}
return syscall.Exec(path, os.Args, os.Environ())
}
示例10: main
func main() {
log.SetFlags(0) // no timestamps on our logs
if len(os.Args) <= 2 {
log.Printf("Usage: %s user-spec command [args]", os.Args[0])
log.Printf(" ie: %s tianon bash", os.Args[0])
log.Printf(" %s nobody:root bash -c 'whoami && id'", os.Args[0])
log.Printf(" %s 1000:1 id", os.Args[0])
log.Println()
log.Printf("%s version: %s (%s on %s/%s; %s)", os.Args[0], Version, runtime.Version(), runtime.GOOS, runtime.GOARCH, runtime.Compiler)
log.Println()
os.Exit(1)
}
// clear HOME so that SetupUser will set it
os.Setenv("HOME", "")
err := SetupUser(os.Args[1])
if err != nil {
log.Fatalf("error: failed switching to %q: %v", os.Args[1], err)
}
name, err := exec.LookPath(os.Args[2])
if err != nil {
log.Fatalf("error: %v", err)
}
err = syscall.Exec(name, os.Args[2:], os.Environ())
if err != nil {
log.Fatalf("error: exec failed: %v", err)
}
}
示例11: envAction
func envAction(c *cli.Context) {
cfg, err := config.LoadConfig()
if err != nil {
log.Fatal(err)
}
args := c.Args()
if len(args) == 0 {
return
}
osEnv := os.Environ()
envMap := make(map[string]string, len(cfg.Rancher.Environment)+len(osEnv))
for k, v := range cfg.Rancher.Environment {
envMap[k] = v
}
for k, v := range util.KVPairs2Map(osEnv) {
envMap[k] = v
}
if cmd, err := exec.LookPath(args[0]); err != nil {
log.Fatal(err)
} else {
args[0] = cmd
}
if err := syscall.Exec(args[0], args, util.Map2KVPairs(envMap)); err != nil {
log.Fatal(err)
}
}
示例12: main
func main() {
if len(os.Args) <= 1 {
os.Exit(0)
}
args := os.Args[1:]
signalWait := 20
if args[0] == "-s" {
signalWait = 0
args = args[1:]
}
interfaceWait := 20 - signalWait
usr2 := make(chan os.Signal)
signal.Notify(usr2, syscall.SIGUSR2)
select {
case <-usr2:
case <-time.After(time.Duration(signalWait) * time.Second):
}
_, err := net.EnsureInterface("ethwe", interfaceWait)
checkErr(err)
binary, err := exec.LookPath(args[0])
checkErr(err)
checkErr(syscall.Exec(binary, args, os.Environ()))
}
示例13: main
func main() {
if len(os.Args) < 2 {
os.Exit(1)
}
pid, errno := fork()
if errno != 0 {
log.Panicf("fork error: %s", errno.Error())
}
if pid != 0 {
// parent
cmd, err := exec.LookPath(os.Args[1])
if err != nil {
log.Panicf("Could not find executable %s",
os.Args[1])
}
syscall.Exec(cmd, os.Args[1:], os.Environ())
}
// child
username, err := exec.Command("whoami").Output()
if err != nil {
log.Panicf("whoami error: %s, out: %s", err, username)
}
if err := spawnSSHD(string(username)); err != nil {
log.Fatal(err)
}
}
示例14: main
func main() {
if len(os.Args) < 2 {
log.Fatalln("Usage: asbox <user> <shell command> [args...]")
}
user, args := os.Args[1], os.Args[2:]
databox, err := isDataboxUser(user)
if err != nil {
log.Fatalln("Unable to determine if", user, "is a databox user:", err)
}
if !databox {
log.Fatalln(user, "is not a databox user")
}
binary, err := exec.LookPath("su")
if err != nil {
log.Fatalln("Unable to find 'su':", err)
}
runtime.LockOSThread()
err = syscall.Setuid(0)
if err != nil {
log.Fatalln("Unable to setuid")
}
args = append([]string{"su", "-", user, "-c", args[0], "--"}, args[1:]...)
err = syscall.Exec(binary, args, os.Environ())
log.Fatalln("Failed to exec:", err)
}
示例15: namespaced
func namespaced() {
dataDir := os.Args[1]
realGraphDir := os.Args[2]
graphDir := filepath.Join(realGraphDir, "graph")
secretGraphDir := os.Args[3]
pidFile := os.Args[4]
mustRun(exec.Command("mount", "--make-slave", dataDir))
mustRun(exec.Command("chmod", "go-x", realGraphDir))
mustBindMountOnce(graphDir, secretGraphDir)
programPath, err := exec.LookPath(os.Args[5])
if err != nil {
fmt.Printf("failed to look path in namespace : %s\n", err)
os.Exit(1)
}
pid := strconv.Itoa(os.Getpid())
err = ioutil.WriteFile(pidFile, []byte(pid), 0644)
if err != nil {
fmt.Printf("failed writing pidfile: %s\n", err)
os.Exit(1)
}
err = syscall.Exec(programPath, os.Args[5:], os.Environ())
if err != nil {
fmt.Printf("exec failed in namespace: %s\n", err)
os.Exit(1)
}
}