开发者

Why is cleanup necessary if both OpenThreadToken and OpenProcessToken fail?

In the IsMemberOfAdministratorsGroup example in MSDN, there i开发者_JAVA技巧s code like this:

if (!OpenThreadToken (GetCurrentThread(), TOKEN_QUERY|TOKEN_DUPLICATE, TRUE, &hToken))
{
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken))
  {
    lastErr = GetLastError();
    goto CLEANUP;
  }
}

....

CLEANUP:
  if (hToken)
  {
     CloseHandle (hToken);
     hToken = NULL;  // Set variable to same state as resource.
  }

I don't see why we need to try to close the token handle if OpenThreadToken() or OpenProcessToken() fails. Is there a special condition when the two functions fail, but the handle is allocated? Or it is simply a typo (they are human anyway)?


If they both fail, hToken will still be 0, and CloseHandle() won't be called....


Your selective editing of the code example hides the fact that in the original code there is a lot of logic between the OpenprocessToken calls and the CLEANUP label. In the normal case (where there is no error on getting one or other of the tokens), CLEANUP is therefore required to close the opened handle.

It's a brute force way of doing try...finally logic that works even if the token handle could not be obtained.

If both calls fail, hToken will be unset and you don't have to close it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜