为什么createProcess()中的argv与普通的c ++程序不同

时间:2016-05-13 13:44:40

标签: c++ winapi

这是我的代码,我发现第一个输出是“thisProgram.exe” 第二个输出是“a”。

为什么?

我在msdn中阅读了doc,但是我不太清楚为什么argv [0]可以是“a”,使用createProcess时在windows中有什么不同。有人可以告诉我与lpApplicationName和lpCommandline的区别吗?感谢

int main( int argc, char *argv[] ) {
cout << argv[0] << endl;

STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

// Start the child process.
if (!CreateProcess("thisProgram.exe",   // No module name (use command line)
                   "a b c",        // Command line
                   NULL,           // Process handle not inheritable
                   NULL,           // Thread handle not inheritable
                   FALSE,          // Set handle inheritance to FALSE
                   0,              // No creation flags
                   NULL,           // Use parent's environment block
                   NULL,           // Use parent's starting directory
                   &si,            // Pointer to STARTUPINFO structure
                   &pi)           // Pointer to PROCESS_INFORMATION structure
        ) {
    printf("CreateProcess failed (%d).\n", GetLastError());
    return 1;
}

// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);

// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;

}

1 个答案:

答案 0 :(得分:2)

CreateProcess将第二个参数(命令行)作为命令行传递给新进程。 CreateProcess不会预先添加模块名称。如果希望应用程序名称显示为argv[0],则必须在命令行参数中重复应用程序名称。

documentation这样说:

  

如果lpApplicationName和lpCommandLine都是非NULL,则lpApplicationName指向的以null结尾的字符串指定要执行的模块,lpCommandLine指向的以null结尾的字符串指定命令行。新进程可以使用GetCommandLine来检索整个命令行。用C编写的控制台进程可以使用argc和argv参数来解析命令行。因为argv [0]是模块名称,所以C程序员通常会重复模块名称作为命令行中的第一个标记。

通常最简单的方法是将NULL传递给应用程序名称,并且命令行传递应用程序名称和连接在一起的参数。

相关问题