子进程如何在自己的目录上工作?

问题描述 投票:0回答:1

考虑一个运行另一个 exe 文件的 Go 程序:

command := exec.Command("C:\\myapplication.exe")
if err := command.Run(); err != nil {
}

并考虑 myapplication.exe 包含以下代码段:

os.Create("generatedfile.txt")

问题在于,generatefile.txt是在父进程的目录中创建的,而不是在子进程的目录(C:\)中创建的。 应该怎样做才能将控制权转移到子进程,以便在子进程的目录中创建文件而不更改 os.Create 中的字符串(即 generatedfile.txt)?

go process
1个回答
0
投票

exec.Cmd Dir 文档说:

Dir 指定命令的工作目录。如果 Dir 是空字符串,则 Run 将在调用进程的当前目录中运行命令。

应用程序未设置

command.Dir
,因此子进程在调用进程的当前目录中运行。

要解决此问题,请将

command.Dir
设置为要运行子进程的目录。

command := exec.Command("C:\\myapplication.exe")
command.Dir = "C:\\some\directory"
if err := command.Run(); err != nil {
}
© www.soinside.com 2019 - 2024. All rights reserved.