【问题标题】:How windows executable knows whether it is opened from consolewindows可执行文件如何知道它是否从控制台打开
【发布时间】:2021-07-14 04:01:58
【问题描述】:

最近我为 Windows 安装了 git-lfs(来自 https://git-lfs.github.com/)。意外地,我试图通过双击在控制台外运行可执行文件“git-lfs.exe”;出现以下消息:

这个提示引起了我的好奇心。通常,从命令行或 Windows 资源管理器运行可执行文件之间没有区别。 windows 可执行文件如何知道它是否已从控制台执行? 假设我们要编写一个程序来检测程序是否从控制台运行。这可以独立于平台编写,还是需要使用平台相关的 API(如How to check if the program is run from a console? 中所述)?

【问题讨论】:

    标签: windows powershell console


    【解决方案1】:

    让我们找出答案!这是一个开源项目,所以代码都在那里供探索(双关语)。

    首先,克隆存储库以便于搜索:git clone https://github.com/git-lfs/git-lfs.git。也可以通过 Github 搜索,但使用本地副本更容易。

    然后,使用grep之类的工具,找到一条错误信息:

    grep -r "command line tool" *
    vendor/github.com/spf13/cobra/cobra.go:var MousetrapHelpText string = `This is a command line tool.
    vendor/github.com/inconshreveable/mousetrap/README.md:Windows developers unfamiliar with command line tools will often "double-click"
    

    看起来有一个包含消息的字符串。捕鼠器是什么东西,用在什么地方?

    grep -r "MousetrapHelpText" *
    vendor/github.com/spf13/cobra/cobra.go:// MousetrapHelpText enables an information splash screen on Windows
    vendor/github.com/spf13/cobra/cobra.go:var MousetrapHelpText string = `This is a command line tool.
    vendor/github.com/spf13/cobra/command_win.go:   if MousetrapHelpText != "" && mousetrap.StartedByExplorer() {
    vendor/github.com/spf13/cobra/command_win.go:       c.Print(MousetrapHelpText)
    

    看起来很有趣。让我们去https://github.com/inconshreveable/mousetrap获取源代码。 command_win.go 文件包含魔法。

    TL;DR:Windows 进程的启动信息包含父进程 ID。如果是同一个 Explorer.exe(Win GUI shell),假设 GUI 启动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      相关资源
      最近更新 更多