Command failed with fork/exec permission denied on MacOS?

Issue

I have a go program that needs to execute another executable program, the program I want to execute from my go code is located in /Users/myuser/bin/ directory and the full path to it would be /Users/myuser/bin/prog

The code is:

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
cmd := exec.Command("prog")
cmd.Dir = "/Users/myuser/bin/"
out, err := cmd.CombinedOutput()
    if err != nil {
        log.Fatalf("cmd.Run() failed with %s\n", err)
    }
    fmt.Printf("combined out:\n%s\n", string(out))
}

When I run the above code on MacOS Mojave I always get the following error:

Command failed with fork/exec /Users/myuser/bin/: permission denied

I’ve seen other answers to similar errors such as Go fork/exec permission denied error and Go build & exec: fork/exec: permission denied but I’m not sure if that’s the case here.

Is it a permissions issue on my machine? or something else can be done from the code?

Solution

OK, I got it to work this way:

  • I ran go clean as leaf bebop mentioned

  • I changed the command execution implementation to:

    func main() {
    cmd := exec.Command("prog")
        cmd.Dir = "/Users/myuser/bin/"
        var out bytes.Buffer
        var stderr bytes.Buffer
        cmd.Stdout = &out
        cmd.Stderr = &stderr
        err := cmd.Run()
        if err != nil {
            fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
            return
        }
        fmt.Println("Result: " + out.String())
    }

Answered By – Mina Wissa

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.