Run a program forever in linux

Running programs indefinitely ensures that services and applications are always available, reliable, and capable of handling real-time data and tasks effectively. So People often want to run programs indefinitely on computers.

In Linux, if you have root access, you can use systemctl to manage services and ensure that they run continuously. Without root access, you can use pm2, a process manager for Node.js applications, to keep programs running. Here’s how you can use both methods:
Using systemctl (with root access)
Create a service file:
Create a new service file in /etc/systemd/system/, for example, myprogram.service.

   [Unit]
   Description=My Program
   After=network.target
   [Service]
   ExecStart=/path/to/your/program
   Restart=always
   User=your-username
   WorkingDirectory=/path/to/working-directory
   [Install]
   WantedBy=multi-user.target

Reload the systemd daemon:

   sudo systemctl daemon-reload

control the service:

   sudo systemctl start|stop|restart|status myprogram.service

Enable the service to start on boot:

   sudo systemctl enable myprogram.service

Using pm2 (without root access)
Install pm2:
If pm2 is not already installed, you can install it using npm:

   npm install pm2 -g

Start your program with pm2:

   pm2 start /path/to/your/program --name myprogram

Ensure pm2 restarts your program on system reboot:

  pm2 save
  pm2 resurrect  //create a cron job @reboot

Both tools ensure that your program runs continuously and can be set to start automatically on system boot.

here’s a table comparing systemctl and pm2:

Featuresystemctlpm2
Access LevelRequires root accessDoes not require root access
InstallationBuilt-in on most Linux distributionsRequires installation via npm
Service ManagementSystem-level service managementUser-level process management
ConfigurationService files in /etc/systemd/system/Managed through pm2 CLI
Startup Script CreationManual setup in service filepm2 startup command
Process MonitoringSystemd handles restarts and monitoringpm2 handles restarts and monitoring
Automatic Restart on FailureYesYes
Logs ManagementJournald (using journalctl to view logs)Built-in logging and monitoring (pm2 logs)
Run at Bootsystemctl enablepm2 save + pm2 startup
Multi-user SupportYesYes
Ease of UseRequires knowledge of systemd unitsSimple and intuitive CLI
Application TypeAny (general-purpose)Mainly for Node.js apps but supports others
Web InterfaceNoYes (pm2-gui for a web dashboard)
Community and DocumentationExtensive documentationExtensive documentation and active community
Additional FeaturesTimers, targets, and dependencies supportLoad balancing, clustering, and more

Leave a Comment