Skip to content

Commit fa53294

Browse files
jklothzooba
authored andcommitted
bpo-34980: P/Invoke QueryFullProcessImageName to get process names (GH-9901)
1 parent 4f399be commit fa53294

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

PCbuild/pyproject.props

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -109,19 +109,34 @@
109109
<FileName Required="true" />
110110
</ParameterGroup>
111111
<Task>
112-
<Code Type="Fragment" Language="cs">
112+
<Using Namespace="System.Diagnostics"/>
113+
<Using Namespace="System.IO"/>
114+
<Using Namespace="System.Runtime.InteropServices"/>
115+
<Using Namespace="System.Text"/>
116+
<Code Type="Method" Language="cs">
113117
<![CDATA[
114-
string fullPath = System.IO.Path.GetFullPath(FileName);
115-
Log.LogMessage("Looking for " + fullPath, MessageImportance.Normal);
116-
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) {
117-
try {
118-
Log.LogMessage("Found running process: " + p.MainModule.FileName, MessageImportance.Low);
119-
if (fullPath.Equals(System.IO.Path.GetFullPath(p.MainModule.FileName), StringComparison.OrdinalIgnoreCase)) {
120-
Log.LogMessage("Terminating " + p.MainModule.FileName, MessageImportance.High);
121-
p.Kill();
118+
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
119+
public static extern bool QueryFullProcessImageName([In]IntPtr hProcess, [In]int dwFlags,
120+
[Out]StringBuilder lpExeName, ref int lpdwSize);
121+
public override bool Execute() {
122+
string fullPath = Path.GetFullPath(FileName);
123+
Log.LogMessage("Looking for " + fullPath, MessageImportance.Normal);
124+
foreach (Process p in Process.GetProcesses()) {
125+
try {
126+
int pathLength = 32768;
127+
StringBuilder pathBuilder = new StringBuilder(pathLength);
128+
if (QueryFullProcessImageName(p.Handle, 0, pathBuilder, ref pathLength)) {
129+
string exeName = Path.GetFullPath(pathBuilder.ToString());
130+
Log.LogMessage("Found running process: " + exeName, MessageImportance.Low);
131+
if (fullPath.Equals(exeName, StringComparison.OrdinalIgnoreCase)) {
132+
Log.LogMessage("Terminating " + exeName, MessageImportance.High);
133+
p.Kill();
134+
}
135+
}
136+
} catch {
122137
}
123-
} catch {
124138
}
139+
return true;
125140
}
126141
]]>
127142
</Code>

0 commit comments

Comments
 (0)