加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

Windows“cmd.exe”是否以不同方式解析参数?

发布时间:2020-12-14 04:00:17 所属栏目:Windows 来源:网络整理
导读:在我看来,Windows cmd.exe解析参数字符串与C编译的exe执行方式有何不同. 为了说明,cmd / C“echo ok”正确打
在我看来,Windows cmd.exe解析参数字符串与C编译的exe执行方式有何不同.

为了说明,cmd / C“echo ok”正确打印“ok”.但是,cmd“/ C”“echo ok”导致

'"echo ok' is not recognized as an internal or external command,operable program or batch file.

为了比较,这里是一个C程序,“CommandArguments.c”,它逐行打印参数:

int main(int argc,char *argv[])
{
    int i;
    for (i = 0; i < argc; ++i) {
        printf("%sn",argv[i]);
    }
}

如果我运行CommandArguments.exe“/ C”“echo ok”,它会正确打印

CommandArguments.exe
/C
echo ok

我问这个是因为我正在实现一个API来包装CreateProcess.我在传递给CreateProcess之前引用并转义所有输入参数.由于上述问题,它适用于大多数事情,但不适用于cmd.

所以,我想知道为什么cmd表现不同?解析规则的论点是什么?有没有其他程序也以不同的方式解析参数?

解决方法

任何应用程序都可以以其认为合适的任何方式解析命令行.大多数应用程序使用C运行时库解析器,但不要求这样做.

理想情况下,您的API应该要求调用者为命令行提供单个字符串而不是参数数组,因为这是启动Windows进程的正确语法.

如果这不可行,那么在目标应用程序需要特殊处理的情况下,您应该至少为呼叫者提供选项.

至于命令处理器,它的解析行为记录在内置帮助(cmd /?)中:

If /C or /K is specified,then the remainder of the command line after
the switch is processed as a command line,where the following logic is
used to process quote (“) characters:

  1. If all of the following conditions are met,then quote characters
    on the command line are preserved:

    • no /S switch
    • exactly two quote characters
    • no special characters between the two quote characters,
      where special is one of: &<>()@^|
    • there are one or more whitespace characters between the
      two quote characters
    • the string between the two quote characters is the name
      of an executable file.
  2. Otherwise,old behavior is to see if the first character is
    a quote character and if so,strip the leading character and
    remove the last quote character on the command line,preserving
    any text after the last quote character.

这有点乱,但您可以通过提供/ S开关来简化它.如果您要运行的命令是[foo],那么只需使用

cmd /s /c "[foo]"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读