Сосбтвенно вот сам код,
import subprocess
import platform
import signal
import os
def kill_process_by_pid(pid):
"""
Attempts to force kill a process by its PID on any operating system.
"""
try:
os_type = platform.system().lower()
if os_type == 'windows':
# Windows command to force kill a process
subprocess.check_call(['taskkill', '/F', '/PID', str(pid)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
print(f"Process {pid} terminated on Windows.")
elif os_type in ['linux', 'darwin', 'freebsd']:
# Linux and macOS (Darwin) command to force kill a process
os.kill(pid, signal.SIGKILL)
print(f"Process {pid} terminated on Unix/macOS.")
else:
print(f"Unsupported operating system: {os_type}")
return False
return True
except OSError as e:
print(f"Error terminating process {pid}: {e}")
return False
except subprocess.CalledProcessError as e:
print(f"Error terminating process {pid} using taskkill: {e}")
return False
# Example usage: Replace with the actual PID of the process you want to kill
# process_to_kill_pid = 12345
# kill_process_by_pid(process_to_kill_pid)
import subprocess
import time
cmd = ["./start.sh"]
p = None# subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
#print(f"Started process with PID {p.pid}")
#p.wait()
#p.kill()
def read_znacheniye() -> int:
with open("./garrysmod/data/stamp.txt") as f:
return float(f.read())
porog = 4
znach1, counter = read_znacheniye(), 0
while True:
time.sleep(1)
diff = read_znacheniye() - znach1
print(counter, "difference", diff)
if diff == 0:
counter += 1
else:
counter = 0
if diff > porog or counter == porog:
counter = 0
if p != None:
kill_process_by_pid(p.pid)
print("Restarting server")
#p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
time.sleep(10)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
time.sleep(40)
znach1 = read_znacheniye()
Смысл простого антикраша в том что бы сверять значение секунд из файла с прошедшим значением. Единственная проблема в том что процесс не завершается когда пытаюсь его закрыть, как быть?
Вот код который должен закрывать процесс.
if p != None:
kill_process_by_pid(p.pid)