do help to check this code as I want MaixiCAM run my python code as soon as it restart…
- 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: syslog
Required-Stop: 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 "(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 "(cat $PID_FILE))" else echo "Not running" fi }
case "0 {start|stop|restart|status}" ;; esac exit 0
- 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):
────────────────────────────────────────
- 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 🐍
────────────────────────────────────────-
PID handling
The PID you save is only the PID of the wrapper shell (nohup /bin/sh -c … &).
When you runstop, youkillthe wrapper, but the Python child might survive (SIGTERM isn’t forwarded automatically). -
Orphan children on reboot / run-level changes
If the wrapper gets killed withSIGHUPorSIGTERM, the loop continues unless the signal is forwarded. -
Mixing-up stdout/stderr redirection and quoting
The heavy quoting innohup /bin/sh -c " while true; do ...is fragile—an unmatched quote will break the entire service.
-
nohup is redundant
init(orsystemd) already detaches the process from the controlling TTY. -
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.targetThen 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 liveThat’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.pyrunit 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!
- What the current script does well ✅
- User
fYI, the os I'm using: Linux maixcam-51a1
- 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:- BusyBox‐only rootfs (classic
/etc/inittab) - SysV-init with
start-stop-daemon - 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/commTypical outputs:
Output What it means Recommended tool systemdYou have systemd Native .serviceunit (simplest)initorbusyboxBusyBox sysvinit Line in /etc/inittabwithrespawninit+/sbin/init -> /lib/sysvinit/initSysV-init Your existing /etc/init.d/…scriptPlease 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’stracking_inout.service—copy-paste,systemctl enable, done.B. BusyBox inittab (pid 1 says
initandbusybox)# /etc/inittab – add near the bottom ti:2345:respawn:/usr/bin/python /root/apps/Tracking_INOUT.py•
respawnmakes BusyBox restart it whenever it exits.
• Reboot or runkill -HUP 1to reread inittab.C. Classic SysV init (what your current script targets)
Keep the script but swap instart-stop-daemonas shown earlier; or move to a supervisor likerunit.──────────────────────────────────────── 🤔 Next step ────────────────────────────────────────
- Run
ps -p 1 -o comm= - 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.
- BusyBox‐only rootfs (classic
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.