执行:在$PATH中未找到可执行文件

21

我正在尝试在Go中向tor发送HUP信号。

    command := exec.Command("pidof tor | xargs kill -HUP")
    command.Dir = "/bin"

    if cmdOut, err := command.CombinedOutput(); err != nil {
        log.Panic("There was an error running HUP ", string(cmdOut), err)
        panic(err)
    }

我尝试了许多版本(有参数/无参数,有/无 Dir 等)但总是返回相同的错误:

2017/06/27 13:36:31 There was an error running HUP exec: "pidof tor | xargs kill -HUP": executable file not found in $PATH
panic: There was an error running HUP exec: "pidof tor | xargs kill -HUP": executable file not found in $PATH

goroutine 1 [running]:
panic(0x639ac0, 0xc42000d260)
        /usr/local/go/src/runtime/panic.go:500 +0x1a1
log.Panic(0xc420049f08, 0x3, 0x3)
        /usr/local/go/src/log/log.go:320 +0xc9
main.main()

在控制台中运行该命令完美无缺:

root@c8927c4a456e:/go/src/github.com/project# pidof tor | xargs kill -HUP
Jun 27 13:40:07.000 [notice] Received reload signal (hup). Reloading config and resetting internal state.
Jun 27 13:40:07.000 [notice] Read configuration file "/etc/tor/torrc".

这是我的$PATH

root@c8927c4a456e:/go/src/github.com/project# echo $PATH
/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

我之前用git命令做过这个操作,而且一切顺利。我是不是漏掉了什么?

1个回答

49
根据文档,传递给exec.Command的第一个参数是可执行文件的名称-仅此而已。它不会被shell解释;它是您想要fork的可执行文件的名称。如果需要传递参数,则可以将它们作为附加参数传递给Command,或者可以在之后将它们传递给返回的对象。
在您的情况下,您正在使用两个命令,并将其中一个的stdout管道连接到另一个的stdin。您可以在纯Go中执行此操作(将一个的Stdout读取器连接到另一个的Stdin写入器),或者可以依赖shell来执行此操作。在后一种情况下,您的可执行文件将是shbash,参数将是["-c", "pidof tor | xargs kill -HUP"]。例如:
cmd := exec.Command("bash", "-c", "pidof tor | xargs kill -HUP")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接