Ili*_* K. 6 c winapi createprocess command-line-arguments
我的C Win32应用程序应该允许为另一个程序传递一个完整的命令行,例如
myapp.exe /foo /bar "C:\Program Files\Some\App.exe" arg1 "arg 2"
Run Code Online (Sandbox Code Playgroud)
myapp.exe 可能看起来像
int main(int argc, char**argv)
{
int i;
for (i=1; i<argc; ++i) {
if (!strcmp(argv[i], "/foo") {
// handle /foo
} else if (!strcmp(argv[i], "/bar") {
// handle /bar
} else {
// not an option => start of a child command line
break;
}
}
// run the command
STARTUPINFO si;
PROCESS_INFORMATION pi;
// customize the above...
// I want this, but there is no such API! :(
CreateProcessFromArgv(argv+i, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
// use startup info si for some operations on a process
// ...
}
Run Code Online (Sandbox Code Playgroud)
我可以考虑一些解决方法:
GetCommandLine()
并找到与argv [i]对应的子字符串ArgvToCommandLine()提到的东西它们都很冗长,并重新实现了繁琐的Windows命令行解析逻辑,这已经是其中的一部分CommandLineToArgvW().
我的问题是否有"标准"解决方案?标准(Win32,CRT等)变通办法的实现算作一种解决方案.
它实际上比你想象的要容易.
1)有一个API,GetCommandLine()它会返回整个字符串
myapp.exe /foo /bar "C:\Program Files\Some\App.exe" arg1 "arg 2"
Run Code Online (Sandbox Code Playgroud)
2)CreateProcess()允许指定命令行,因此使用它作为
CreateProcess(NULL, "c:\\hello.exe arg1 arg2 etc", ....)
Run Code Online (Sandbox Code Playgroud)
将完全满足您的需求.
3)通过解析命令行,您可以找到exe名称的起始位置,并将该地址传递给CreateProcess().它可以轻松完成
char* cmd_pos = strstr(GetCommandLine(), argv[3]);
Run Code Online (Sandbox Code Playgroud)
最后: CreateProcess(NULL, strstr(GetCommandLine(), argv[i]), ...);
编辑:现在我看到你已经考虑过这个选项了.如果您担心性能损失,那么它们与流程创建无关.