SSH: Run program that stays alive after exit session

Lets say I have a headless Pi at home and Its life is going to be running a program forever.
For our example lets say the program is something boring like:

fn main() -> () {
   loop() {}
}

So I ssh into it and run the program.
When I exit session that terminal and the program will die, I assume.

Is that right? What is the typical way to get around this.

Hey Pix,

You’ve got a couple of options depending if you want to have the program run in the background, run in a session you can connect into to, or if you want to have it start at boot.

To have it run in the background, even if you disconnect, use the nohup (no hang up) command:

sudo nohup [your_command] >[your_log_file] 2>&1 &

This will run the program in the background and output any errors to the log file.

Alternatively, you can use the screen program to create and detach from terminals:

sudo apt install screen
sudo screen -S [programScreen]

This will bring up the new terminal. Run your program and then disconnect via ctrl + alt + delete.

You can then list your screens with:

sudo screen -ls

And resume the session with the PID:

sudo screen -r -d [PID]

Alternatively, you can always have it start on boot which would save a lot of the hassle.

In all of these cases, the program will run until it comes to an end. For a loop, that means running until you either kill its PID or the you turn the machine off.

1 Like

This is what I was looking for. A nice alternative to screen. Perfect.

1 Like