|
1 | 1 | import logging |
2 | 2 | import os |
3 | 3 | import re |
| 4 | +import psutil |
4 | 5 | import requests |
5 | 6 | import subprocess |
6 | 7 | import sys |
@@ -299,6 +300,13 @@ def __init__( |
299 | 300 | creationflags=creationflags, |
300 | 301 | ) |
301 | 302 | self.browser_pid = browser.pid |
| 303 | + self._process_pid = browser.pid |
| 304 | + try: |
| 305 | + self._process_create_time = ( |
| 306 | + psutil.Process(self._process_pid).create_time() |
| 307 | + ) |
| 308 | + except psutil.NoSuchProcess: |
| 309 | + self._process_create_time = None |
302 | 310 | service_ = None |
303 | 311 | log_output = subprocess.PIPE |
304 | 312 | if patch_driver: |
@@ -392,6 +400,22 @@ def _hook_remove_cdc_props(self, cdc_props): |
392 | 400 | }, |
393 | 401 | ) |
394 | 402 |
|
| 403 | + def is_running(self): |
| 404 | + """Check if the browser is still running.""" |
| 405 | + if not getattr(self, "_process_pid", None): |
| 406 | + return False |
| 407 | + # Not good enough: return psutil.pid_exists(self._process_pid) |
| 408 | + try: |
| 409 | + process = psutil.Process(self._process_pid) |
| 410 | + # Check for PID recycling: Is this actually our process? |
| 411 | + if hasattr(self, "_process_create_time"): |
| 412 | + if process.create_time() != self._process_create_time: |
| 413 | + return False # The PID was reused by a different process! |
| 414 | + # If the process is a zombie, assume the browser isn't running |
| 415 | + return process.status() != psutil.STATUS_ZOMBIE |
| 416 | + except psutil.NoSuchProcess: |
| 417 | + return False |
| 418 | + |
395 | 419 | def remove_cdc_props_as_needed(self): |
396 | 420 | cdc_props = self._get_cdc_props() |
397 | 421 | if len(cdc_props) > 0: |
|
0 commit comments