Suspend, Background, Disown
I'm currently working on a hobby project, using crawlers to download media files for a dataset. Some of these are large files that also need preprocessing. Instead of building a whole system to manage this, I'm just creating simple scripts to handle them one at a time.
Given the volume of data I'm working with, I realized the scripts were going to take a long time to run on my mini-server. So, I needed to run them as background processes.
In the past, I've always relied on nohup
or tmux
for this kind of thing. But today, I remembered a neat trick I recently learned.
Suspend the Process
It turns out you can suspend a process that's already running. While your script or command is active, just press CTRL + Z
. You'll get a message like this:
[1]+ Stopped (your command)
The [1]
is the job number of the process.
Resume in the Background
After you suspend the process, you can type bg
and hit enter. This command will resume the job, but it will run in the background now.
[1]+ (your command) &
It will confirm that it's running in the background, usually with a message ending in that notable ampersand (&
).
Disown the Process
This is the most important part of the trick. The process is still attached to your current shell session, so you need to detach (or disown) it. The main reason I always stuck with nohup
in the past was to prevent the process from stopping when I logged out.
To disown it, you simply enter:
disown -h %1
The %1
refers to the job number. Now the process is fully independent of your session.
What's wrong with nohup?
Nothing, really. The main difference is you use nohup
before you start a process. The trick above lets you do it after a process is already running. That's what makes it so neat!
Final Thoughts
Of course, tmux
detached sessions still rule, but for simple things like this, I find this is a handy trick. It's especially useful when I'm on a server that doesn't have tmux
installed and I don't have permission to add it. Meh.