Golang exec:在文件被移动到那里后,stat:没有这样的文件或目录

huangapple go评论86阅读模式
英文:

Golang exec: stat: no such file or directory after file has been moved there

问题

我有一个脚本,我正在使用"os/exec"包进行部署。我使用的其中一个命令如下:

cpInit = exec.Command("cp", "initScripts/nginx", "/etc/init.d/nginx")

还有另一个命令:

startNginx = exec.Command("/etc/init.d/nginx", "start")

最初,我使用err := cpInit.Run()运行第一个命令,但是后来当我运行第二个命令时,我收到了错误信息:

exec: "/etc/init.d/nginx": stat /etc/init.d/nginx: 没有那个文件或目录

但是当程序退出时,/etc/init.d/nginx是存在的,所以我想也许第一个命令没有完成(即使Run()会等待命令返回)。我将Run()更改为Start()Wait(),但结果相同。有人可以告诉我为什么第二个命令找不到那个文件吗?

英文:

I have a script that I am using for deployment using the "os/exec" package. One of the commands that I use is as follows:

cpInit = exec.Command("cp", "initScripts/nginx", "/etc/init.d/nginx")

and another:

startNginx = exec.Command("/etc/init.d/nginx", "start")

Initially I ran the first command with err := cpInit.Run(), but later when I run the second command I get the error:

exec: "/etc/init.d/nginx": stat /etc/init.d/nginx: no such file or directory

But when the program exits /etc/init.d/nginx is there, so I thought maybe the first command didn't finished (even though Run() waits until the command returns). I changed Run() to Start() and Wait() only to get the same results. Can anyone tell me why the second command can't find that file?

答案1

得分: 5

当你运行exec.Command(...)时,它会立即检查文件是否存在,但必须推迟错误直到你调用Run(),因为Command()调用不会返回错误。

在这里可以看到Command的定义:http://golang.org/src/pkg/os/exec/exec.go?s=3410:3455#L99

它调用了这里定义的LookPath(...):http://golang.org/src/pkg/os/exec/lp_unix.go?s=902:944#L23

在调用复制命令的Run()之后,你需要在确认文件存在之后初始化Command

英文:

When you run exec.Command(...) it immediately goes and checks for the file's existence, but has to defer the error until you call Run(), because the Command() call doesn't return an error.

See here for the definition of Command: http://golang.org/src/pkg/os/exec/exec.go?s=3410:3455#L99

It calls LookPath(...) defined here: http://golang.org/src/pkg/os/exec/lp_unix.go?s=902:944#L23

You need to initialize the Command after you know the file is there--after calling Run() on your copy command.

huangapple
  • 本文由 发表于 2013年12月12日 23:54:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/20548064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定