Exec and Working Directory

Hello Go-mates,

I am trying to use the Dir variable (Working Directory), however I am running into a problem as I do this:

cmd := exec.Command(m.Job.Command, args...)
cmd.Env = envs
cmd.Dir = m.Job.WorkingDir

When I do (at a later point):

cmd.Run()

It doesn’t work, infact the problem begins at the Command call as LookPath inside it returns an error and assigns it to lookPathErr. This variable is checked inside the Start command and prevents further execution.

I can create my own Command function but this should work out of the box right?

Thanks,
Daniel

What does the error say? I mean is there any other hint as to what the is going on. There could be a number of things on the operating system side interfering, like permissions and the like. More info would be helpful to solving this.

1 Like

Yes, more info would be useful!

OS is Windows 10

I have created a ‘service’ application that runs processes on ‘other’ machines, e.g. runners in Gitlab. I want this service application to run an .exe in another directory, e.g. c:\mytestprocess

The ‘exec’ package works fine when myprocess is in PATH, however I want to cater for when it isn’t, and a working directory is specified. I assume the Cmd.Dir member is what I can use to do this?

When I call run I get a ‘executable file not found in %PATH%’ error. Debugging the code in exec.go reveals that Cmd.lookPathErr gets assigned an err inside the exec.Command call as described above, and this variable is checked inside (c *Cmd) Start() at the very beginning.

Hopefully this helps

The command is always searched in the PATH, if you want to specify one specific that is in a certain directory, you need to specify an absolute PATH when creating the exec.Command.

Working dir is exactly this. The directory that the executable is working in. Usually it is that you started it from when on a terminal.

I guess I am interpreting this incorrectly:

// Dir specifies the working directory of the command.
// If Dir is the empty string, Run runs the command in the
// calling process’s current directory.
Dir string

As I do not know how you interpret it, I can’t tell if you are interpreting it correctly.

Dir sets the working directory. It does not influence the search path at all.

In windows though, the working directory is always prepended to the search path when using a terminal. But not when you use system calls to run a child process.

Ok, got the two conflated. Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.