To restart a Python process after it exits without paying for a supervisor, a small watchdog can check for it and launch it again. The key is identifying the right process: checking a known child PID is precise, while searching /proc or using pgrep can match the wrong process. For an unattended service, systemd is usually the better place to configure restarts.
Choose how to identify the process
There are two different problems: monitoring a child process that your Python program started, and finding a process that was started independently.
As an Amazon Associate I earn from qualifying purchases.
| Method | What it tracks | Best suited to |
|---|---|---|
subprocess.Popen |
A child launched by the current Python process; its PID and exit state. | A Python watchdog that owns the process it launches. |
pgrep or /proc |
Processes selected by name or command line. | Checking for an independently launched process, provided the match is distinctive. |
systemd Restart= |
A process managed as a systemd service. | Unattended service lifecycle and restart handling. |
If your program launches the worker, keep the returned Popen object and use poll() to see whether it has exited. Python documents Popen.pid as the spawned child’s process ID; poll() reports whether it has completed, while wait() waits for completion. This avoids guessing identity from a process name. See the Python subprocess documentation.
A minimal watchdog pattern using pgrep
For an independently started process, a watchdog can look for a distinctive command-line string and start the program if no match is found. This illustrative shell loop checks every five seconds:
#1 Best Overall
- 12th Intel Alder Lake N95 Processor – The GMKtec G3 S Mini PC is powered by the 12th Gen Intel N95 processor with 4 cores, 4 threads, 6MB cache and a burst frequency up to 3.4GHz. Compared with N100/N5105/N5100/N5095, the N95 delivers up to 36% overall performance improvement. Perfect for routine tasks, office work, and home entertainment, this compact mini desktop is more convenient than traditional bulky PCs.
- 8GB RAM & 256GB SSD Storage – Pre-installed with 8GB DDR4 memory and a fast 256GB M.2 2242 SSD, the G3 S mini desktop offers quicker startup, smoother multitasking, and faster file transfers. Enjoy seamless performance whether you’re working on multiple applications, browsing, or streaming content.
- Rich Interfaces & Connectivity – The G3 S mini computer comes equipped with USB 3.2 (up to 10Gbps), dual HDMI 2.0 (4K@60Hz), and a 3.5mm audio jack. With support for WiFi 5, Bluetooth 5.0, and Gigabit Ethernet (RJ45 1000MbE), it connects easily with monitors, projectors, printers, office equipment, and other peripherals, making it versatile for both home and business use.
- Dual 4K Display Support – Featuring upgraded Intel UHD Graphics (up to 1000MHz), the G3 S supports 4K video playback and AV1 decoding for a smooth viewing experience. With dual HDMI outputs, you can connect two 4K@60Hz displays simultaneously, enabling efficient multitasking for work and entertainment.
- GMKTEC WARRANTY - GMKtec offers a 3-year limited warranty (1 year replacement + 2 years parts replacement) for each mini PC, starting from the date of the purchase effective on all sales starting Oct. 2026. All defects due to design and workmanship are covered. With a professional after sales team always ready to attend to your needs, you can simply relax and enjoy your mini PC
#!/bin/sh
pattern='python3 /opt/myapp/worker.py'
while :; do
if ! pgrep -f -x "$pattern" >/dev/null; then
/usr/bin/python3 /opt/myapp/worker.py &
fi
sleep 5
done
Replace the executable and script path with the actual paths on your system. The quoted variable prevents shell word-splitting and glob expansion, and -x asks pgrep for an exact full-command-line match. Confirm that the command line used by the running process is exactly the pattern you specify; interpreter options, wrappers, or different paths can change it. This is a simple restart loop, not a guarantee that a worker is healthy or that the match is unique.
Why process matching can restart the wrong program
Default process-name matching is short
By default, pgrep matches a process name. Linux process names exposed through /proc/PID/stat are limited to 15 characters, so a longer name may be truncated and may not distinguish similar processes.
-f searches the full command line
With -f, pgrep searches the full command line exposed through /proc/PID/cmdline. That gives you more identifying detail, but a broad pattern can match unrelated processes. Use a distinctive exact command line when possible and check its behavior before relying on it. The pgrep manual documents the matching options and process-name limitation.
Rank #2
- 【AMD Ryzen 3 5300U CPU: Outperforms N150 & 3500U】 BOSGAME E5 mini PC is powered by the TSMC 7nm FinFET architecture AMD Ryzen 3 5300U processor (4 Cores, 8 Threads, up to 3.8GHz boost, 6MB total cache). Compared to low-end Intel N150 or 3500U chips which only have 4 single threads and throttle under load, the 5300U delivers over 30% faster multi-core speed. Run 30+ browser tabs, large Excel sheets, and Zoom meetings simultaneously without system lag.
- 【8GB DDR4 RAM & 256GB NVMe SSD Storage】 Installed with high-speed 8GB DDR4 dual-channel memory and a fast 256GB M.2 2280 SSD, eliminating slow boot times and application loading delays. To accommodate growing data requirements, the upgradeable hardware design features dual SODIMM slots that allow you to expand memory up to 64GB RAM, ensuring smooth operation during heavy multitasking.
- 【High-Capacity Dual M.2 SSD Storage Expansion】 Never worry about running out of space for your business files. In addition to the pre-installed 256GB system drive, the motherboard houses an extra empty internal M.2 2280 NVMe PCIe 3.0 slot. This allows you to easily add a second solid-state drive for up to an additional 2TB of storage capacity (upgrades not included) without needing to remove or reinstall the original operating system.
- 【Radeon 6-Core Graphics & Triple 4K Displays】 Integrated with official AMD Radeon Graphics (6 Graphics Cores, 1500 MHz frequency) for casual gaming, photo editing, and crisp 4K media decoding. Featuring 1x HDMI 2.0 port, 1x DisplayPort, and 1x Full-Function Type-C port, the E5 outputs true 4K@60Hz resolution to three monitors at once. This multi-screen setup eliminates constant window-switching for traders, programmers, and office workers.
- 【Dual 2.5GbE LAN Ports for Advanced Networking】 Experience fast wired network transmission speeds up to 2500Mbps without lagging or buffering. The integration of dual 2.5 Gigabit Ethernet ports (powered by Realtek RTL8125 controller) makes this compact computer an exceptional hardware choice for tech enthusiasts. Easily configure it into software routers, hardware firewalls (pfSense, OpnSense), home NAS servers, or local homelabs.
Checking a PID is not the same as finding a process
Testing whether /proc/1234 exists answers whether that PID currently has a proc entry; it does not establish that the process is the intended worker. PIDs can be reused after a process exits. For a child you launched, use the Popen object instead. For an independently started program, match identifying details carefully rather than treating any live PID as the right one.
Use systemd for an unattended Linux service
If the goal is to keep a service running after an ordinary exit, configure it as a systemd service and choose a Restart= policy appropriate to the failure conditions you want systemd to handle. The policy determines which exits and failures trigger a restart; consult the systemd.service(5) manual for the available policies and unit behavior.
For example, a service unit can include a restart policy under its [Service] section:
Rank #3
- 【1-Year Worry-Free Warranty】Your satisfaction is our priority. Glorlin provides a 1-year warranty covering any hardware malfunctions. We support returns or exchanges to ensure a 100% worry-free shopping experience. Have a question? Reach out to us through our official after-sales email for a prompt solution.
- 【Reliable Performance with Ryzen 7 Processor】Powered by AMD Ryzen 7 8745HS (8 cores, 16 threads, up to 4.9GHz), this mini pc delivers stable performance for daily workloads. Suitable for office tasks, programming, and multitasking, it works well as a ryzen mini pc for both home and business use.
- 【Radeon 780M Graphics for Media and Light Gaming】Equipped with integrated Radeon 780M graphics, this mini gaming pc supports smooth 4K video playback and handles many popular games at adjusted settings. A practical mini computer for media, editing, and casual gaming.
- 【Mini PC 16GB RAM and Fast Storage】This mini pc 16gb ram configuration includes single 16GB DDR5 memory (4800MHz,3GB is assigned to VRAM by default) and a 1TB NVMe SSD, offering quick boot times and responsive system performance. Dual M.2 slots allow storage expansion up to 4TB for growing files and projects.
- 【Quad 4K Display Support for Productivity】The mini desktop computer supports up to four 4K displays via HDMI, DisplayPort, and dual USB-C ports. Ideal for multi-screen workflows such as coding, trading, or content creation with improved efficiency.
[Service]
ExecStart=/usr/bin/python3 /opt/myapp/worker.py
Restart=on-failure
This is a unit fragment, not a complete service file. It assumes the script and interpreter are at those paths; a complete unit also needs the appropriate service type and installation details for the host.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Restart= and WatchdogSec= do different jobs
Restart= responds to process exit or failure conditions. By contrast, systemd’s WatchdogSec= expects the service to send regular liveness notifications using sd_notify(3). The systemd manual says, “The service must call sd_notify(3) regularly with "WATCHDOG=1" (i.e. the "keep-alive ping").” If those messages stop, systemd treats the service as failed. A process that is alive but stuck may need health reporting; a loop that only detects process absence will not detect that condition.
Handle shell commands safely
When Python invokes a shell explicitly, Python’s documentation places responsibility for quoting whitespace and shell metacharacters on the application. Prefer passing an argument sequence to subprocess rather than building a shell command string, and do not interpolate untrusted input into shell commands. This helps prevent malformed commands and shell injection; it does not solve the separate challenge of correctly identifying a process.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




