Go build & exec: fork/exec: permission denied

筅森魡賤 提交于 2020-05-13 14:27:32

问题


I need to build a program using the Go toolchain and then execute it. For some reasons I get a permission error due the forking. Is there a way to circumvent this error or any best practice? I think my program does something similar with Go test tool, though go test doesn't get this kind of error.

package main

import(
    "os"
    "os/exec"
    "flag"
    log "github.com/golang/glog"
)

func main(){
    flag.Parse()
    tdir := "abc"
    if err := os.MkdirAll(tdir, 0777); err !=nil{
        log.Error(err)
        return
    }
    f, err := os.Create(tdir + "/main.go")
    if err !=nil{
        log.Error(err)
        return
    }
    if err = f.Chmod(0777); err !=nil{
        log.Error(err)
        return
    }
    defer f.Close()
    defer os.Remove(f.Name())
    if _, err = f.Write([]byte(tpl)); err !=nil{
        log.Error(err)
        return
    }
    cmd := exec.Command("go", "build", "-o", "edoc")
    cmd.Path = tdir
    b, err := cmd.CombinedOutput()
    if err !=nil{
        log.Errorf("%s, err %v", b, err)
        return
    }

}

var tpl = `package main

import(
    "fmt"
    "flag"
)

func main(){
    flag.Parse()
    fmt.Printf("Hello World")

}`

Error:

E0202 18:24:42.359008   13600 main.go:36] , err fork/exec abc: permission denied

OS: OSX 10.11


回答1:


You're changing the command path from the location of your go binary, to abc.

type Cmd struct {
        // Path is the path of the command to run.
        //
        // This is the only field that must be set to a non-zero
        // value. If Path is relative, it is evaluated relative
        // to Dir.
        Path string

If you want to change the working directory, use Cmd.Dir



来源:https://stackoverflow.com/questions/35159117/go-build-exec-fork-exec-permission-denied

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!