C# では、テスト用にブラウザーを起動します。PID を取得して、winforms アプリケーションで開始された残りのゴースト プロセスを強制終了できるようにします。
driver = new FirefoxDriver();
PID を取得するにはどうすればよいですか?
C# では、テスト用にブラウザーを起動します。PID を取得して、winforms アプリケーションで開始された残りのゴースト プロセスを強制終了できるようにします。
driver = new FirefoxDriver();
PID を取得するにはどうすればよいですか?
Selenium固有ではなく、C#の質問のように見えます。
これは非常に古い非決定論的な回答です。これを試してみたい場合は、再検討してください。
私の論理は、Process.GetProcessesByName Methodfirefox
を使用して名前を持つすべてのプロセス PID を取得し、次に を開始してから、プロセスの PID を再度取得し、それらを比較して開始したばかりの PID を取得することです。この場合、特定のドライバーによって開始されたプロセスの数は問題ではありません (たとえば、Chrome は複数開始され、Firefox は 1 つだけ開始されます)。FirefoxDriver
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Firefox;
namespace TestProcess {
[TestClass]
public class UnitTest1 {
[TestMethod]
public void TestMethod1() {
IEnumerable<int> pidsBefore = Process.GetProcessesByName("firefox").Select(p => p.Id);
FirefoxDriver driver = new FirefoxDriver();
IEnumerable<int> pidsAfter = Process.GetProcessesByName("firefox").Select(p => p.Id);
IEnumerable<int> newFirefoxPids = pidsAfter.Except(pidsBefore);
// do some stuff with PID if you want to kill them, do the following
foreach (int pid in newFirefoxPids) {
Process.GetProcessById(pid).Kill();
}
}
}
}
親プロセス ID を使用してみてください:
public static Process GetWindowHandleByDriverId(int driverId)
{
var processes = Process.GetProcessesByName("chrome")
.Where(_ => !_.MainWindowHandle.Equals(IntPtr.Zero));
foreach (var process in processes)
{
var parentId = GetParentProcess(process.Id);
if (parentId == driverId)
{
return process;
}
}
return null;
}
private static int GetParentProcess(int Id)
{
int parentPid = 0;
using (ManagementObject mo = new ManagementObject($"win32_process.handle='{Id}'"))
{
mo.Get();
parentPid = Convert.ToInt32(mo["ParentProcessId"]);
}
return parentPid;
}
プロセス ID を取得して強制終了するには、Process
クラスを使用します。関心の方法は次のとおりです。
プロセスを名前で解決したら、そのプロパティを照会できます。ID を取得しますprocess.Id
。Google Chrome などの一部のブラウザでは、実行中のプロセスが複数あることに注意してください (Chrome では、タブごとに少なくとも 1 つの実行中のプロセスがあります)。したがって、それを強制終了したい場合は、すべてのプロセスを強制終了する必要があります。