Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

do help to check this code as I want MaixiCAM run my python code as soon as it restart…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Mistralmagistral-medium-2506’s answer.
  1. User

    do help to check this code as I want MaixiCAM run my python code as soon as it restart or crash

    #!/bin/sh

    BEGIN INIT INFO

    Provides: tracking_inout

    Required-Start: remotefsremote_fs syslog

    Required-Stop: remotefsremote_fs syslog

    Default-Start: 2 3 4 5

    Default-Stop: 0 1 6

    Short-Description: Run Tracking_INOUT.py on boot

    END INIT INFO

    SCRIPT="/root/apps/Tracking_INOUT.py" PYTHON="/usr/bin/python" PID_FILE="/var/run/tracking_inout.pid" LOG_FILE="/var/log/tracking_inout.log"

    start() { echo "Starting Tracking_INOUT script..." if [ -f "PID_FILE" ] && kill -0 (cat "$PID_FILE") 2>/dev/null; then echo "Script already running." return 1 fi

    nohup /bin/sh -c "
    	while true; do
    		echo \"[$(date)] Starting script\" >> $LOG_FILE
    		$PYTHON $SCRIPT >> $LOG_FILE 2>&1
    		echo \"[$(date)] Script crashed. Restarting in 5 seconds...\" >> $LOG_FILE
    		sleep 5
    	done
    " &
    echo $! > "$PID_FILE"
    echo "Script started with PID $(cat $PID_FILE)"
    

    }

    stop() { echo "Stopping Tracking_INOUT script..." if [ -f "PIDFILE"];thenkillPID_FILE" ]; then kill (cat "PID_FILE") 2>/dev/null && echo "Stopped." rm -f "PID_FILE" else echo "PID file not found. Is the script running?" fi }

    status() { if [ -f "PID_FILE" ] && kill -0 (cat "PIDFILE")2>/dev/null;thenecho"Running(PIDPID_FILE") 2>/dev/null; then echo "Running (PID (cat $PID_FILE))" else echo "Not running" fi }

    case "1"instart)start;;stop)stop;;restart)stop;sleep1;start;;status)status;;∗)echo"Usage:1" in start) start ;; stop) stop ;; restart) stop; sleep 1; start ;; status) status ;; *) echo "Usage: 0 {start|stop|restart|status}" ;; esac exit 0

  2. Assistant

    Below is a line-by-line review of your SysV init script, common failure points, and two alternative approaches that are usually more robust on modern embedded Linux images (including most MaixCAM builds):

    ────────────────────────────────────────

    1. What the current script does well ✅
      ──────────────────────────────────────── • Registers the service in the classic /etc/init.d style (BEGIN INIT INFO block).
      • Writes a PID file so you can query status / stop it.
      • Wraps your Python script in an endless loop so it restarts after a crash.
      • Logs to /var/log/tracking_inout.log.

    ──────────────────────────────────────── 2. Things that can bite you 🐍
    ────────────────────────────────────────

    1. PID handling
      The PID you save is only the PID of the wrapper shell (nohup /bin/sh -c … &).
      When you run stop, you kill the wrapper, but the Python child might survive (SIGTERM isn’t forwarded automatically).

    2. Orphan children on reboot / run-level changes
      If the wrapper gets killed with SIGHUP or SIGTERM, the loop continues unless the signal is forwarded.

    3. Mixing-up stdout/stderr redirection and quoting
      The heavy quoting in

      nohup /bin/sh -c "
          while true; do
              ...
      

      is fragile—an unmatched quote will break the entire service.

    4. nohup is redundant
      init (or systemd) already detaches the process from the controlling TTY.

    5. Using sleep 5
      If the script exits instantly in a busy-loop crash you’ll hammer your CPU.
      A back-off mechanism is safer (sleep 5 → sleep 10 → sleep 30 …).

    ──────────────────────────────────────── 3. Quick-fix if you must stay on SysV init
    ──────────────────────────────────────── Replace your start() and stop() functions like so:

    start() {
        echo "Starting Tracking_INOUT..."
        if [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE") 2>/dev/null; then
            echo "Already running."
            return 0
        fi
    
        # Start the wrapper in its own process group (-m) so we can kill the whole tree.
        start-stop-daemon --start --background \
            --pidfile "$PID_FILE" --make-pidfile \
            --chdir /root/apps \
            --exec /bin/bash -- -c "
                echo '[wrapper] pid $$' >> $LOG_FILE
                while true; do
                    echo \"[\$(date)] launching python\" >> $LOG_FILE
                    exec $PYTHON $SCRIPT >> $LOG_FILE 2>&1
                    RET=\$?
                    echo \"[\$(date)] python exited \$RET\" >> $LOG_FILE
                    sleep 5
                done
            "
    }
    
    stop() {
        echo "Stopping Tracking_INOUT..."
        if [ -f "$PID_FILE" ]; then
            # --retry ensures children also die
            start-stop-daemon --stop --pidfile "$PID_FILE" --retry 10
            rm -f "$PID_FILE"
            echo "Stopped."
        else
            echo "Not running."
        fi
    }
    

    Why start-stop-daemon? It handles
    • creation/removal of pidfiles,
    • killing a process group so the Python child doesn’t dangle,
    • retry/timeout logic.

    Add it to the top: which start-stop-daemon || (echo "Install dpkg or busybox version" && exit 1)

    ──────────────────────────────────────── 4. A better 2024 approach: systemd ⏩
    ──────────────────────────────────────── Most recent Sipeed / MaixCAM images ship with systemd enabled. A one-file systemd unit gives you:

    • Automatic restarts (Restart=on-failure)
    • Journal logging (no manual redirection / log-rotation needed)
    • Timeout handling, resource limits, dependency ordering, etc.

    Create /etc/systemd/system/tracking_inout.service

    [Unit]
    Description=Run Tracking_INOUT.py (auto-restart)
    After=network.target
    
    [Service]
    Type=simple
    Environment=PYTHONUNBUFFERED=1
    ExecStart=/usr/bin/python /root/apps/Tracking_INOUT.py
    WorkingDirectory=/root/apps
    Restart=on-failure          # restart unless exit 0
    RestartSec=5                # 5s delay
    StandardOutput=append:/var/log/tracking_inout.log
    StandardError=append:/var/log/tracking_inout.log
    
    # Optional resource limits / nice value
    # LimitCORE=infinity
    # Nice=5
    
    [Install]
    WantedBy=multi-user.target
    

    Then enable & start:

    sudo systemctl daemon-reload
    sudo systemctl enable  tracking_inout.service   # start at boot
    sudo systemctl start   tracking_inout.service
    sudo systemctl status  tracking_inout.service  # view status
    # logs:
    journalctl -u tracking_inout.service -f        # follow live
    

    That’s it—systemd’s built-in watchdog will do the respawn loop for you.

    ──────────────────────────────────────── 5. Even lighter: runit / s6 / supervisord
    ──────────────────────────────────────── If your firmware excludes systemd and you dislike the old SysV style, drop-in supervisors like runit or s6 are trivial to use:

    /etc/service/tracking_inout/run
    --------------------------------
    #!/bin/sh
    exec 2>&1
    exec /usr/bin/python /root/apps/Tracking_INOUT.py
    

    runit automatically respawns on exit. Done.

    ──────────────────────────────────────── 6. Summary 🚀
    ──────────────────────────────────────── • Your current init script is OK but can leave orphaned Python processes.
    • Swap in start-stop-daemon if you want to keep SysV style.
    • Prefer a native process supervisor (systemd / runit / s6) for cleaner, safer restarts and logging.

    Pick whichever option fits the image running on your MaixCAM; most users go with systemd nowadays for its simplicity.

    Happy hacking!

  3. User

    fYI, the os I'm using: Linux maixcam-51a1

  4. Assistant

    Got it — thanks for the hint.
    “Linux maixcam-51a1” doesn’t tell us which init system is running; MaixCAM firmware images have appeared in at least three flavours:

    1. BusyBox‐only rootfs (classic /etc/inittab)
    2. SysV-init with start-stop-daemon
    3. Yocto-generated images that boot with full systemd

    The right way to auto-restart your script depends on which of those you have, so let’s identify it first.

    ──────────────────────────────────────── 🔍 1 – Find out what pid 1 is ──────────────────────────────────────── Run one of these on the camera’s shell:

    # Option A
    ps -p 1 -o comm=
    
    # Option B
    ls -l /proc/1/exe
    
    # Option C
    cat /proc/1/comm
    

    Typical outputs:

    OutputWhat it meansRecommended tool
    systemdYou have systemdNative .service unit (simplest)
    init or busyboxBusyBox sysvinitLine in /etc/inittab with respawn
    init + /sbin/init -> /lib/sysvinit/initSysV-initYour existing /etc/init.d/… script

    Please run the command and let me know what you get; then I can hand you the exact, cut-and-paste ready snippet.

    ──────────────────────────────────────── 📜 2 – If you want to try each approach anyway ──────────────────────────────────────── A. systemd service (works only if pid 1 is systemd)
    See the previous message’s tracking_inout.service—copy-paste, systemctl enable, done.

    B. BusyBox inittab (pid 1 says init and busybox)

    # /etc/inittab  – add near the bottom
    ti:2345:respawn:/usr/bin/python /root/apps/Tracking_INOUT.py
    

    • respawn makes BusyBox restart it whenever it exits.
    • Reboot or run kill -HUP 1 to reread inittab.

    C. Classic SysV init (what your current script targets)
    Keep the script but swap in start-stop-daemon as shown earlier; or move to a supervisor like runit.

    ──────────────────────────────────────── 🤔 Next step ────────────────────────────────────────

    1. Run ps -p 1 -o comm=
    2. Paste the result here → I’ll answer with the exact config for that init system.

    That way we’re sure you get a rock-solid auto-restart on MaixCAM.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.