themihai
themihai

Reputation: 8631

Go build & exec: fork/exec: permission denied

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

Upvotes: 2

Views: 8055

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109347

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

Upvotes: 4

Related Questions