go语言执行一个二进制程序时为什么写绝对路径反而不对啊?

时间:2023-02-16

浏览:296

作者:佚名

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《go语言执行一个二进制程序时为什么写绝对路径反而不对啊?》,聊聊go,希望可以帮助到正在努力赚钱的你。

问题内容

cmd := exec.Command("./proxy")
cmd.Run()

比如写绝对路径程序是不会运行的,相对路径就可以

正确答案

从代码上看的话,应该是允许处理绝对路径的命令的:
os/exec/exec.go:117

// Command returns the Cmd struct to execute the named program with
// the given arguments.
//
// It sets only the Path and Args in the returned structure.
//
// If name contains no path separators, Command uses LookPath to
// resolve name to a complete path if possible. Otherwise it uses name
// directly as Path.
//
// The returned Cmd's Args field is constructed from the command name
// followed by the elements of arg, so arg should not include the
// command name itself. For example, Command("echo", "hello").
// Args[0] is always name, not the possibly resolved Path.
func Command(name string, arg ...string) *Cmd {
    cmd := &Cmd{
        Path: name,
        Args: append([]string{name}, arg...),
    }
    if filepath.Base(name) == name {
        if lp, err := LookPath(name); err != nil {
            cmd.lookPathErr = err
        } else {
            cmd.Path = lp
        }
    }
    return cmd
}

注释上说,如果

name
参数中含有路径分隔符(linux/unix 是
/
)则直接用提供的路径,如果不含有路径分隔符,会用环境变量中的
path
来取得最终的命令路径。

本篇关于《go语言执行一个二进制程序时为什么写绝对路径反而不对啊?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页