在 C 程序中,我试图构建一个将在系统调用中使用的字符串:
char myCommands[128];
...
/* packing myCommands string */
..
system(myCommands);
要执行的命令字符串如下所示:
setEnvVars.bat & xCmd.exe ...command-paramters...
如果“...command-parameters...”不包含任何引号字符,则一切正常,语句成功。
如果“...command-parameters...”包含任何引号字符,我会收到此错误:
The filename, directory name, or volume label syntax is incorrect.
例子:
setEnvVars.bat & xCmd.exe -e "my params with spaces"
另一件奇怪的事情是,如果我将 myCommands 字符串逐字放入 *.bat 文件中,引号和所有内容都可以完美运行。
“system(...)”有什么不同?
== 好的,更多详细信息==
我有一个演示问题的简单程序。此版本确实有效:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char cmdStr[1024];
strcpy(cmdStr, "\"C:\\Windows\\system32\\cmd.exe\" /c echo nospaces & C:\\Windows\\system32\\cmd.exe /c echo moretext");
printf("%s\n", cmdStr);
system(cmdStr);
}
输出:
"C:\Windows\system32\cmd.exe" /c echo nospaces & C:\Windows\system32\cmd.exe /c echo moretext
nospaces
moretext
这不工作:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char cmdStr[1024];
strcpy(cmdStr, "\"C:\\Windows\\system32\\cmd.exe\" /c echo nospaces & \"C:\\Windows\\system32\\cmd.exe\" /c echo moretext");
printf("%s\n", cmdStr);
system(cmdStr);
}
输出:
"C:\Windows\system32\cmd.exe" /c echo nospaces & "C:\Windows\system32\cmd.exe\" /c echo moretext
The filename, directory name, or volume label syntax is incorrect.
我认为它可能与“cmd.exe/S”选项有关,但尝试引入该选项不会改变行为。
不需要 cmd.exe 路径周围的引号,因为没有空间,但在我的目标程序中,我试图允许所有安装路径,其中可能包括“C:\Program Files”
(那个认为在路径名中有空格是个好主意的人的痘痘。)
(并且使用单引号不会改变行为。)
最佳答案
经过一段时间的思考,我放弃了“system(cmdLine)”方法,转而使用“CreateProcess”调用(这将在 Windows 下运行)。
使用 CreateProcess 我能够避开整个环境变量问题,这就是导致我尝试使用“cmd1 & cmd2”语法的原因。
CreateProcess 将允许您将不同的环境传递给子进程。我能够弄清楚如何重写环境并将其传递给 child 。这巧妙地解决了我的问题。
我重写环境的代码可能有点麻烦,但它可以工作并且看起来相当健壮。
关于c - Windows 上 C 程序中的系统调用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15034074/