Puppeteer Sharp: How to kill all running Chrome.exe instances created by one browser initialization?

298 Views Asked by At

I know this is a quite old question, but I have a problem with too many instances created and not cleaned up after use.

I using a Windows Forms application and the latest C# version.

I have an application that runs 2 separate puppeteer processes. These 2 processes are run successively many times, in loops.

When creating a browser, there are opened 4 to 5 “chrome” processes, each with their own ProcessId. I can only get one of these ProcessId from the browser object created.

The first browser returns ProcessId = 23728:

using (IBrowser browser = await Puppeteer.LaunchAsync(lo))
{
    ProcessId.Add(browser.Process.Id);

But it has also created the following processes:

chrome.exe  23728   Running ps  00  8.368 K Not allowed
chrome.exe  32064   Running ps  00  1.304 K Not allowed
chrome.exe  18300   Running ps  00  11.520 K    Not allowed
chrome.exe  27624   Running ps  00  10.288 K    Not allowed
chrome.exe  1976    Running ps  00  8.728 K Not allowed

When I later create another browser object then this is also creating 4 to 5 new processes.

When looping then the number of processes gets quite high.

Even I have the browser created inside a USING this is not cleaned up after the application closes.

I can kill all of them by running:

Process[] chromeInstances = Process.GetProcessesByName("chrome");

foreach (Process p in chromeInstances)
{
    p.Kill();
}

But is there a way to get the ProcessId of all the chrome instances that one browser create, so I can kill only those that is associated to one instance of a browser creation? So I can clean up manually after each browser is closed?

1

There are 1 best solutions below

0
Wouter van Nifterick On

You could check if the chrome process you're trying to kill is a child of the current process.

Something like this:

Process currentProcess = Process.GetCurrentProcess();
Process[] chromeInstances = Process.GetProcessesByName("chrome");

foreach (Process p in chromeInstances)
{
    if(currentProcess.Id == p.Parent.Id){
      p.Kill();
    }
}

If your application terminates it's too late. The chrome.exe instances that puppeteer instantiates will become orphaned. I just ran in to that here. I've killed all chrome instances like this:

taskkill /F /IM chrome.exe