Main entry point for daemon.
()
| 880 | |
| 881 | |
| 882 | def main() -> int: |
| 883 | """Main entry point for daemon.""" |
| 884 | # Parse command-line arguments |
| 885 | foreground = "--foreground" in sys.argv |
| 886 | |
| 887 | # Setup logging |
| 888 | setup_logging(foreground=foreground) |
| 889 | |
| 890 | # Ensure daemon directory exists |
| 891 | DAEMON_DIR.mkdir(parents=True, exist_ok=True) |
| 892 | |
| 893 | if foreground: |
| 894 | # Run in foreground (for debugging) |
| 895 | logging.info("Running in foreground mode") |
| 896 | # Write PID file even in foreground mode for testing |
| 897 | with open(PID_FILE, "w") as f: |
| 898 | f.write(str(os.getpid())) |
| 899 | try: |
| 900 | run_daemon_loop() |
| 901 | finally: |
| 902 | PID_FILE.unlink(missing_ok=True) |
| 903 | return 0 |
| 904 | |
| 905 | # Check if daemon already running |
| 906 | if PID_FILE.exists(): |
| 907 | try: |
| 908 | with open(PID_FILE, "r") as f: |
| 909 | existing_pid = int(f.read().strip()) |
| 910 | if psutil.pid_exists(existing_pid): |
| 911 | logging.info(f"Daemon already running with PID {existing_pid}") |
| 912 | print(f"Daemon already running with PID {existing_pid}") |
| 913 | return 0 |
| 914 | else: |
| 915 | # Stale PID file |
| 916 | logging.info(f"Removing stale PID file for PID {existing_pid}") |
| 917 | PID_FILE.unlink() |
| 918 | except KeyboardInterrupt as ki: |
| 919 | handle_keyboard_interrupt(ki) |
| 920 | raise |
| 921 | except Exception as e: |
| 922 | logging.warning(f"Error checking existing PID: {e}") |
| 923 | PID_FILE.unlink(missing_ok=True) |
| 924 | |
| 925 | # Use daemoniker to properly daemonize |
| 926 | try: |
| 927 | daemonizer_context = Daemonizer() |
| 928 | with daemonizer_context as (is_setup, daemonizer): # type: ignore[misc] |
| 929 | if is_setup: |
| 930 | # Pre-daemon setup (runs as parent process) |
| 931 | logging.info("Initializing daemon") |
| 932 | |
| 933 | # Daemonize (this returns twice - once in parent, once in child) |
| 934 | # Note: On Windows, pid_file must be the first positional arg, not a keyword arg |
| 935 | result = daemonizer( |
| 936 | str(PID_FILE), # pid_file (first positional arg) |
| 937 | chdir=str(Path.home()), |
| 938 | ) |
| 939 | # Unpack result - may be just is_parent or (is_parent,) |
no test coverage detected