Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Stop HasProcessExited from leaking process handles #603

Merged
merged 1 commit into from
Jul 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions WinApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public static class WinApi

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);

/// <summary>
/// Flag that specifies the access rights to query limited information about a process.
Expand All @@ -54,13 +56,24 @@ internal static bool HasProcessExited(int processId)
}

bool exited;
if (!WinApi.GetExitCodeProcess(hProcess, out uint exitCode))

try
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
if (!WinApi.GetExitCodeProcess(hProcess, out uint exitCode))
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}

// Fun fact, If a program uses STILL_ACTIVE (259) as an exit code, GetExitCodeProcess will return 259, since it returns... the exit code. This would break this function.
exited = exitCode != 259;
// Fun fact, If a program uses STILL_ACTIVE (259) as an exit code, GetExitCodeProcess will return 259, since it returns... the exit code. This would break this function.
exited = exitCode != 259;
}
finally
{
// Imagine closing process handles.
WinApi.CloseHandle(hProcess);
}


return exited;
}
}
Expand Down