|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import time |
| 4 | +import logging |
| 5 | +from setproctitle import setproctitle |
| 6 | + |
| 7 | +#setproctitle("ProcessWatch") |
| 8 | +os.makedirs(os.getcwd() + "/pid", exist_ok=True) |
| 9 | +os.makedirs(os.getcwd() + "/logs", exist_ok=True) |
| 10 | +pid_file = (f"{str(os.getcwd())}/pid/processwatch.pid") |
| 11 | +log_file = (f"{str(os.getcwd())}/logs/processwatch.log") |
| 12 | +output_file = (f"{str(os.getcwd())}/processwatch.out") |
| 13 | + |
| 14 | +# Configure Logging |
| 15 | +logging.basicConfig( |
| 16 | + filename=log_file, |
| 17 | + level=logging.INFO, |
| 18 | +) |
| 19 | + |
| 20 | +# Write PID File |
| 21 | +def write_pid_file(): |
| 22 | + try: |
| 23 | + with open(pid_file, 'w', encoding="utf-8") as f: |
| 24 | + f.write(str(os.getpid())) |
| 25 | + setproctitle(f"Process Watch - PID {str(os.getpid())}") |
| 26 | + except Exception as e: |
| 27 | + logging.error("An error occurred writing the daemon pid file: %s", e, exc_info=True) |
| 28 | + raise sys.exit(1) |
| 29 | + |
| 30 | +# Read PID File |
| 31 | +#def read_pid_file(): |
| 32 | +# try: |
| 33 | +# with open(pid_file, 'r', encoding="utf-8") as f: |
| 34 | +# pid_number = int(f.read().strip()) |
| 35 | +# except Exception as e: |
| 36 | +# logging.error("An error occurred reading the daemon pid file: %s", e, exc_info=True) |
| 37 | +# raise sys.exit(1) |
| 38 | + |
| 39 | +# Daemonize |
| 40 | +def processwatch(): |
| 41 | + |
| 42 | + # Fork the first child process |
| 43 | + pid = os.fork() |
| 44 | + if pid > 0: |
| 45 | + # Exit the parent process |
| 46 | + sys.exit(0) |
| 47 | + |
| 48 | + # Become a session leader |
| 49 | + os.setsid() |
| 50 | + |
| 51 | + # Fork the second child process |
| 52 | + pid = os.fork() |
| 53 | + if pid > 0: |
| 54 | + # Exit the first child process |
| 55 | + sys.exit(0) |
| 56 | + |
| 57 | + # Change the working directory to the root directory |
| 58 | + os.chdir(os.getcwd()) |
| 59 | + |
| 60 | + # Close standard file descriptors |
| 61 | + os.close(0) |
| 62 | + os.close(1) |
| 63 | + os.close(2) |
| 64 | + |
| 65 | + # Redirect standard file descriptors to /dev/null |
| 66 | + os.open(os.devnull, os.O_RDWR) |
| 67 | + os.dup2(0, 1) |
| 68 | + os.dup2(0, 2) |
| 69 | + |
| 70 | + write_pid_file() |
| 71 | + |
| 72 | + # Run Daemon Logic |
| 73 | + while True: |
| 74 | + try: |
| 75 | + with open(output_file, "a", encoding="utf-8") as f: |
| 76 | + f.write(f"Daemon running at {time.ctime()}\n") |
| 77 | + time.sleep(10) |
| 78 | + except Exception as e: |
| 79 | + logging.error("An error occurred in the daemon: %s", e, exc_info=True) |
| 80 | + raise sys.exit(1) |
| 81 | + |
| 82 | +if __name__ == "__main__": |
| 83 | + processwatch() |
0 commit comments