Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
singlestore-labs
GitHub Repository: singlestore-labs/singlestoredb-python
Path: blob/main/singlestoredb/apps/_process.py
469 views
1
import os
2
import signal
3
import typing
4
if typing.TYPE_CHECKING:
5
from psutil import Process
6
7
8
def kill_process_by_port(port: int) -> None:
9
existing_process = _find_process_by_port(port)
10
kernel_pid = os.getpid()
11
# Make sure we are not killing current kernel
12
if existing_process is not None and kernel_pid != existing_process.pid:
13
print(f'Killing process {existing_process.pid} which is using port {port}')
14
os.kill(existing_process.pid, signal.SIGKILL)
15
16
17
def _find_process_by_port(port: int) -> 'Process | None':
18
try:
19
import psutil
20
except ImportError:
21
raise ImportError('package psutil is required')
22
23
for proc in psutil.process_iter(['pid']):
24
try:
25
connections = proc.connections()
26
for conn in connections:
27
if conn.laddr.port == port:
28
return proc
29
except psutil.AccessDenied:
30
pass
31
32
return None
33
34