| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367 |
2x
2x
2x
2x
2x
2x
2x
17x
17x
17x
7x
7x
7x
7x
2x
79x
79x
79x
79x
79x
79x
79x
79x
79x
5428x
5428x
5428x
58x
1x
57x
58x
28x
30x
5398x
79x
79x
49x
2x
54x
54x
52x
2x
2x
1x
1x
54x
2x
24x
24x
24x
24x
2x
18x
18x
2x
6x
6x
2x
3x
3x
3x
3x
3x
3x
262x
262x
262x
262x
1x
1x
3x
3x
1x
1x
2x
1x
1x
1x
3x
2x
37x
37x
1x
36x
36x
37x
37x
37x
37x
37x
37x
37x
37x
37x
36x
37x
37x
2x
2x
| /*
* Windows Process Handling.
* A wrapper to integrate processHandlingCore into GPII.
*
* Copyright 2016 Raising the Floor - International
*
* Licensed under the New BSD license. You may not use this file except in
* compliance with this License.
*
* The research leading to these results has received funding from the European Union's
* Seventh Framework Programme (FP7/2007-2013)
* under grant agreement no. 289016.
*
* You may obtain a copy of the License at
* https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
"use strict";
var fluid = require("universal");
var ref = require("ref");
var gpii = fluid.registerNamespace("gpii");
var windows = fluid.registerNamespace("gpii.windows");
require("../WindowsUtilities/WindowsUtilities.js");
var c = windows.API_constants;
/**
* Kills any windows processes with a given application filename.
* http://stackoverflow.com/questions/7956519/how-to-kill-processes-by-name-win32-api
*
* @param {String} The filename of the application. For example, the Windows on
* screen keyboard is "osk.exe". Other examples include "Magnify.exe" and
* "firefox.exe".
*/
gpii.windows.killProcessByName = function (filename) {
var pids = gpii.windows.findProcessByName(filename, true);
Eif (pids) {
for (var n = 0, len = pids.length; n < len; n++) {
var hProcess = windows.kernel32.OpenProcess(c.PROCESS_TERMINATE, 0, pids[n]);
Eif (hProcess !== ref.NULL) {
windows.kernel32.TerminateProcess(hProcess, 9);
windows.kernel32.CloseHandle(hProcess);
}
}
}
};
/**
* Finds a running process with the given name.
*
* The CreateToolhelp32Snapshot Windows API call captures the running processes, and the Process32First/Next
* functions are used to enumerate them.
*
* @param filename The exe file name to search for, null to match any.
* @param all {boolean?} Set to true to return an array containing all matching processes.
* @param fullInfo {boolean?} Set to true to return the pid, ppid, and exe name of matching processes.
* @returns {?number|number[]} The Process ID of the matching processes, otherwise null.
*/
gpii.windows.findProcessByName = function (filename, all, fullInfo) {
// Get a snapshot of the processes.
var hSnapShot = windows.kernel32.CreateToolhelp32Snapshot(windows.API_constants.TH32CS_SNAPPROCESS, null);
Iif (hSnapShot === windows.API_constants.INVALID_HANDLE_VALUE) {
console.error("CreateToolhelp32Snapshot failed. Win32 error: " + windows.GetLastError());
return null;
}
var matches = [];
var filenameLower = filename && filename.toLowerCase();
try {
// Create the structure for the return parameter of Process32First/Next.
var pEntry = new windows.PROCESSENTRY32();
pEntry.dwSize = windows.PROCESSENTRY32.size;
// Enumerate the processes.
var hRes = windows.kernel32.Process32First(hSnapShot, pEntry.ref());
while (hRes) {
var buf = new Buffer(pEntry.szExeFile);
var processName = ref.readCString(buf, 0);
if (!filename || processName.toLowerCase() === filenameLower) {
var proc;
if (fullInfo) {
proc = {
pid: pEntry.th32ProcessID,
ppid: pEntry.th32ParentProcessID,
exeFile: processName
};
} else {
proc = pEntry.th32ProcessID;
}
if (all) {
// Add it to the array of matches.
matches.push(proc);
} else {
// Only want the first one - return it.
return proc;
}
}
hRes = windows.kernel32.Process32Next(hSnapShot, pEntry.ref());
}
} finally {
// Make sure the snapshot is closed.
Eif (hSnapShot) {
windows.kernel32.CloseHandle(hSnapShot);
}
}
return all ? matches : null;
};
/**
* Determines if a given process is running, returning true if it is.
*
* @param proc {string|number} The name of the executable, or the process ID.
* @return {boolean} true if the process is running.
*/
gpii.windows.isProcessRunning = function (proc) {
var togo = false;
if (isNaN(proc)) {
togo = gpii.windows.findProcessByName(proc) !== null;
} else {
try {
process.kill(proc, 0);
togo = true;
} catch (e) {
togo = false;
}
}
return togo;
};
/**
* Waits for a process to either start or terminate, returning a promise which will resolve when the existence of a
* process is in the desired state.
*
* The promise will reject if the process has yet to become in the desired state after the timeout.
*
* @param proc {string|number} The name of the executable, or the process ID.
* @param options The options.
* @param options.start The desired state: true to wait for the process to start, false to wait for the termination.
* @param options.timeout Approximate milliseconds to wait, or null for infinite.
* @param options.pollDelay How long to wait, in milliseconds, between checking for the process.
* @return {promise} The promise will resolve when the process is in the desired state, or will reject if after the
* timeout the process is still in the same state.
*/
gpii.windows.waitForProcessState = function (proc, options) {
var defaultOptions = {
pollDelay: 500,
timeout: null,
start: false
};
options = fluid.extend(true, defaultOptions, options);
var waitOptions = {
argument: proc,
conditionValue: options.start,
pollDelay: options.pollDelay,
timeout: options.timeout,
error: {
isError: true,
message: "Timed out waiting for process " + proc +
" to " + (options.start ? "start" : "terminate") + " after " + options.timeout + "ms"
}
};
return gpii.windows.waitForCondition(gpii.windows.isProcessRunning, waitOptions);
};
/**
* Waits for a process to terminate, returning a promise which will resolve when there are no matching processes
* running. If there are no processes running when the function is called, the promise will already be resolved.
* The promise will reject if the process is still running after the timeout.
*
* @param proc {string|number} The name of the executable, or the process ID.
* @param userOptions The options.
* @param userOptions.timeout Approximate milliseconds to wait, or null for infinite.
* @param userOptions.pollDelay How long to wait, in milliseconds, between checking for the process.
* @return {promise} The promise will resolve when there are no matching processes running, or will reject if a matching
* process is still running after the timeout.
*/
gpii.windows.waitForProcessTermination = function (proc, userOptions) {
var options = fluid.extend(true, {start: false}, userOptions);
return gpii.windows.waitForProcessState(proc, options);
};
/**
* Waits for a process to start, returning a promise which will resolve when there there is a matching process running.
* If there are already processes running when the function is called, the promise will already be resolved.
* The promise will reject if a matching process is still not running after the timeout.
*
* @param proc {string|number} The name of the executable, or the process ID.
* @param userOptions The options.
* @param userOptions.timeout Approximate milliseconds to wait, or null for infinite.
* @param userOptions.pollDelay How long to wait, in milliseconds, between checking for the process.
* @return {promise} The promise will resolve when there is a matching processes running, or will reject if a matching
* process is still not running after the timeout.
*/
gpii.windows.waitForProcessStart = function (proc, userOptions) {
var options = fluid.extend(true, {start: true}, userOptions);
return gpii.windows.waitForProcessState(proc, options);
};
/**
* Terminates a process in a kind manner by sending WM_QUIT to the windows it owns. This should allow the process to
* perform any clean up tasks.
*
* If options.gracefulOnly is false (default), and if the process has not shutdown after the timeout or the process
* does not have any Windows, then the process will be terminated.
*
* The returned promise resolves when the process has ended, with a boolean indicating whether a clean shutdown was
* possible.
*
* @param filename
* @param options The options.
* @param options.timeout How long to wait for the process to die, in milliseconds.
* @param options.cleanOnly true to reject if the process can't be closed cleanly; false to force the termination.
* @param options.exitCode {number} The exit code the application should return.
* @return {promise}
*/
gpii.windows.closeProcessByName = function (filename, options) {
var defaultOptions = {
timeout: 15000,
cleanOnly: false,
exitCode: 0
};
options = fluid.extend(defaultOptions, options);
var pids = gpii.windows.findProcessByName(filename, true);
Iif (!pids) {
// Process is not running.
return fluid.toPromise(true);
}
var foundWindow = false;
// Enumerate all the top-level windows on the desktop, to see which ones are owned by the process.
gpii.windows.enumerateWindows(function (hwnd) {
// Get the process ID that owns the Window.
var ptr = ref.alloc(windows.types.DWORD);
gpii.windows.user32.GetWindowThreadProcessId(hwnd, ptr);
var windowPid = ptr.deref();
if (pids.indexOf(windowPid) !== -1) {
// Send WM_QUIT, which tells the thread to terminate.
gpii.windows.user32.PostMessageW(hwnd, windows.API_constants.WM_QUIT, options.exitCode, 0);
foundWindow = true;
}
});
var promiseTogo = fluid.promise();
if (foundWindow) {
// Wait for the process to die.
gpii.windows.waitForProcessTermination(filename, { timeout: options.timeout })
.then(function () {
promiseTogo.resolve(true);
}, function (err) {
// Taking too long to die.
if (options.cleanOnly) {
promiseTogo.reject({
isError: true,
message: "Process " + filename + " will not close cleanly: " + err.message,
error: err
});
} else {
// Force it to terminate
gpii.windows.killProcessByName(filename);
// This promise was rejected but the return promise should resolve as the process is terminated.
promiseTogo.resolve(false);
}
});
} else {
// The process does not have any windows so it can't be shutdown cleanly.
if (options.cleanOnly) {
promiseTogo.reject({
isError: true,
message: "Process " + filename + " will not close cleanly: No windows belong to the process"
});
} else {
// Force it to terminate.
gpii.windows.killProcessByName(filename);
promiseTogo.resolve(false);
}
}
return promiseTogo;
};
/**
* Gets the path to the executable of a running process.
*
* Provide the processHandle if it's available when calling, otherwise provide the pid.
*
* @param pid {Number} [Optional] The process ID.
* @param processHandle [Optional] The process handle.
* @return {String} The path to the executable.
*/
gpii.windows.getProcessPath = function (pid, processHandle) {
var hProcess;
var togo = null;
if (processHandle) {
hProcess = processHandle;
} else Eif (pid) {
hProcess =
gpii.windows.kernel32.OpenProcess(gpii.windows.API_constants.PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
} else {
fluid.fail("Either pid or processHandle needs to be given.");
}
Eif (hProcess) {
try {
var size = ref.alloc(gpii.windows.types.DWORD);
size.writeUInt32LE(gpii.windows.API_constants.MAX_PATH, 0);
var path = new Buffer(gpii.windows.API_constants.MAX_PATH);
var success = gpii.windows.kernel32.QueryFullProcessImageNameW(hProcess, 0, path, size);
Eif (success) {
togo = gpii.windows.fromWideChar(path);
}
} finally {
if (hProcess !== processHandle) {
gpii.windows.kernel32.CloseHandle(hProcess);
}
}
}
Iif (!togo) {
// OpenProcess or QueryFullProcessImageName failed (usually due to permissions). Get the file name from the
// process list instead.
var all = gpii.windows.findProcessByName(null, true, true);
var process = all.find(function (p) {
return p.pid === pid;
});
if (process) {
togo = process.exeFile;
}
}
return togo;
};
fluid.defaults("gpii.windows.killProcessByName", {
gradeNames: "fluid.function",
argumentMap: {
filename: 0
}
});
fluid.defaults("gpii.windows.closeProcessByName", {
gradeNames: "fluid.function",
argumentMap: {
filename: 0,
options: 1
}
});
|