In the following I will show you how you can detach a process from the session and keep a Process/Command alive when you close your Linux Terminal
Have you ever wanted to run a long process or a bot in the background on your Linux server even when you close the connection? Or are you scared of suddenly losing your connection and losing the work of a long-running task?
Luckily, there are 2 ways of accomplishing this.
The first is using screen, a terminal multiplexer - a terminal multiplexer that lets you start a screen session and then open any number of virtual terminals within that session.
Processes running in these virtual terminals / screens will continue to run even though their window is not visible or when you disconnect.
The alternative to screen is actually more of a way of scheduling processes on Linux - Cron Jobs. But it may be the right tool for your job.
Cron lets you run automated commands at specific times, dates and intervals. Similar to screen, it also runs in the background and works even when you closed your SSH connection.
But let's look at “screen” first.
Using screen to keep process running in background after ending SSH session
- SSH into your Server using Putty, OpenSSH or whatever tool you like.
sudo apt install screenOR
sudo yum install screen(depends on your Linux Distro) to install screen if it is not already installed.
- Start a new screen session using the following Command:
screen -S session_name
- Now run whatever Command you want to run in the background
- Press CTRL-A and then CTRL-D. This will detach you from your screen session, but leave the processes running. You can close the SSH Connection now, if you want to.
- If you want to come back later you can now type:
screen -lsto see all currently running screen sessions.
- If you want to open one of these sessions you can type:
screen -r session_name(You can also use the Session ID which is the first number before the dot instead of the session_name)
- You can also close a screen session using:
screen -S session_name -Xquit (You can also use the Session ID instead of the session_name)
Using Crontab to schedule task to run
To schedule a Cron Job on Linux you have to edit the “crontab” file.
- This can be done using the following command:
- Now you can edit the file just like a text file. Add this at the end of the file to run a python script at 5 am every day for example:
0 5 * * * python3 /root/main.pyOR
10 30 * * sun /root/backup.shto run the “backup.sh” file every Sunday at 10 30 am (See this post for more examples)
- Now save the crontab file using CTRL-O and then pressing enter
- Now Close the crontab file editor using CTRL-X