关于c ++:CreateProcess成功,但是GetLastError()返回拒绝访问

CreateProcess succeeds, but GetLastError() returns access denied

由于CreateProcess()GetLastError()的返回值冲突,我有些困惑。 当我以类似于下面的方式使用CreateProcess()时,它会成功执行并似乎已完成其所需的任务。 但是,GetLastError()仍然返回"访问被拒绝"。

如果访问被拒绝,为什么它会完成任务。 相反,如果CreateProcess()成功,为什么GetLastError()返回访问被拒绝?

还是我对GetLastError()的使用不正确? 我只能在CreateProcess()返回失败值时使用它吗? (我对以下行为的辩解是,我认为安全胜于后悔)

1
2
3
4
5
6
7
8
9
10
    SetLastError(0);
    hello = CreateProcess(_T("C:\\\\Windows\\\\System32\\\\cmd.exe"),
        _T("C:\\\\Windows\\\\System32\\\\cmd.exe /C ant debug"),
        NULL,NULL,false,0,NULL,
        _T("C:\\\\My\\\\Directory"),&siStartupInfo, &piProcessInfo);
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ALLOCATE_BUFFER
        |FORMAT_MESSAGE_IGNORE_INSERTS,NULL,GetLastError(),
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&errorText, 0, NULL);
    AfxMessageBox(errorText);

这种行为正常吗? 在CreateProcess()文档中,它提到了CreateProcess()失败时使用GetLastError()的情况,但没有提及相反的情况。 不批评文档,只是想澄清一下。

无论CreateProcess()中的第二个参数是否为NULL,都会发生这种情况。 也许与cmd.exe权限有关? 如果是这种情况,CreateProcess()应该不会失败? 谢谢。


GetLastError的文档中

The Return Value section of the documentation for each function that sets the last-error code notes the conditions under which the function sets the last-error code. Most functions that set the thread's last-error code set it when they fail. However, some functions also set the last-error code when they succeed. [emphasis mine]

我认为您得到了有经验的结果,因为成功完成CreateProcess不会设置错误值GetLastError返回。 相反,您对GetLastError的调用将返回由先前调用的另一个函数设置的错误


GetLastError仅在文档指出有意义时才有意义。

GetLastError返回Win32线程使用SetLastError设置的最后一个错误。 因为函数仅应在记录或清除最后一个错误时设置或清除它们,否则,如果尚未发生,则最后一个错误很可能包含不相关的较早错误。

据记录,CreateProcess如果失败则设置最后的错误,而不是成功。 因此,您应该忽略它。