考虑Windows 10上的以下CMD会话,以#
注释开头的行:
# We have this simple program
D:\testdir>type prg.c
#include <stdio.h>
int main() {
printf("Hello prg");
return 0;
}
# This is "realgcc.exe (Rev2, Built by MSYS2 project) 6.2.0"
D:\testdir>gcc prg.c -o prg
D:\testdir>prg.exe
Hello prg
D:\testdir>md dir
D:\testdir>cd dir
D:\testdir\dir>..\prg.exe
Hello prg
# This does not work however
D:\testdir\dir>../prg.exe
'..' is not recognized as an internal or external command,
operable program or batch file.
# But this does
D:\testdir\dir>"../prg.exe"
Hello prg
# Now we want to call the same program, from the same directory,
# but from C instead, so we create this file
D:\testdir\dir>type call.c
#include <stdlib.h>
int main() {
system("..\\prg.exe");
return 0;
}
D:\testdir\dir>gcc call.c -o call
D:\testdir\dir>call.exe
Hello prg
# Now to the question: If we modify the system function call
# to the following -- why doesn't it work?
D:\testdir\dir>type call.c
#include <stdlib.h>
int main() {
system("\"../prg.exe\"");
return 0;
}
D:\testdir\dir>gcc call.c -o call
D:\testdir\dir>call.exe
'..' is not recognized as an internal or external command,
operable program or batch file.
因此,显然调用system
与在CMD会话中交互式运行命令不同吗?报价是否由于某些原因而被删除?是否存在另一种语法,可以使用包含使用/
而不是\
作为分隔符的相对路径来调用其他目录中的可执行文件?
(我在尝试使Cygwin程序和通常的Windows程序相互通信时注意到这一点。)
编辑:显然,这工作:
#include <stdlib.h>
int main() {
system("\"\"../prg.exe\"\"");
return 0;
}
在CMD中可能相关
cmd /c ""../prg.exe""
可行,但这不可行
cmd /c "../prg.exe"
因此,似乎出于某种原因在system
通话中需要一些额外的报价吗?
感谢您提供所有有用的评论,我现在了解发生了什么。system
在询问此问题时,我没有考虑命令(即的参数)实际上是如何传递给“命令解释器”的,因此考虑理解外部引号为何消失至关重要。
在Windows上,调用与使用参数和system("command")
产生新cmd.exe
进程本质上是相同的。(在Linux和类似的操作系统上,我们将与等效。)/c
command
sh -c command
但是,这里的问题是,在大多数情况下,当命令通过/c
标志传递时,Windows的CMD会删除第一个和最后一个引号字符。这在以下文档给出的文档中进行了说明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.
[...]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句