c - 将 argv[] 传递给 CreateProcess() 的方法

标签 c winapi command-line-arguments createprocess

我的 C Win32 应用程序应该允许传递完整的命令行以启动另一个程序,例如

myapp.exe /foo /bar "C:\Program Files\Some\App.exe" arg1 "arg 2"

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
  // ...
}

我可以考虑一些解决方法:

两者都很冗长,重新实现了繁琐的windows命令行解析逻辑,这已经是CommandLineToArgvW()的一部分了。 .

是否有针对我的问题的“标准”解决方案?变通办法的标准(Win32、CRT 等)实现算作解决方案。

最佳答案

实际上比您想象的要容易。

1) 有一个 API,GetCommandLine() 会返回整个字符串

myapp.exe /foo /bar "C:\Program Files\Some\App.exe" arg1 "arg 2"

2) CreateProcess() 允许指定命令行,因此将其用作

CreateProcess(NULL, "c:\\hello.exe arg1 arg2 etc", ....) 

将完全满足您的需求。

3) 通过解析命令行,您可以找到 exe 名称的起始位置,并将该地址传递给 CreateProcess() 。可以用

轻松完成
char* cmd_pos = strstr(GetCommandLine(), argv[3]);

最后:CreateProcess(NULL, strstr(GetCommandLine(), argv[i]), ...);

编辑:现在我看到您已经考虑过这个选项。如果您担心性能损失,那么与流程创建相比,它们无足轻重。

关于c - 将 argv[] 传递给 CreateProcess() 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3982602/

相关文章:

C vector 作为 char *** vector

c - 为什么在写入使用字符串初始化的 "char *s"时会出现段错误,而不是 "char s[]"?

c - 如何以编程方式扩展卷

arrays - C 中 int 的参差不齐的数组

bash - 是否可以使用多个命令行参数运行 matlab 函数?

linux - 如何在 Linux 命令行中将多个输入指定为单个输入?

c - 如何停止循环并等待从串行接收到不同的值

c - 使用 Turbo C++ 3.0 编译器的 C 语言程序的令人困惑的输出

windows - Windows 上的 OpenGL 1.0 和 1.1 函数指针

.net - Google 身份验证 [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] 返回 UNAUTHORIZED