Linux’s method of running commands or programs in the terminal background (Ubuntu / Fedora / CentOS, etc.)



When we log in remotely with terminal tools such as SecureCRT, we often need to execute a program, but we hope that the program can continue to run in the background after the user logs off or the terminal is closed. Here are several methods and precautions:

Method 1: add after the command&

Generally, add &, and then press enter to execute the command:

[email protected]:/var/www/html/doc$ node server &

Method 2: press Ctrl + Z after running the command

If your command is to execute a program that does not exit, for example:

[email protected]:/var/www/html/doc$ node server

Then it will always block the console and can’t enter other commands.
At this time, if you want this program to run in the background, pressctrl+zIt can be transferred to the background; You can release the console for other operations.

Method 3: use BG command

If the program is already running in the foreground before you operate, to retrieve the program, enter it firstjobs, check the program to be retrieved and remember the number on the left; Re inputBG number, done.

[email protected]:/var/www/html/doc$ jobs
[1] + sudo node server stopped
[email protected]:/var/www/html/doc$ bg 1

One thing to pay special attention to

For commands involving user permissions, if you want to run them in the background, you must run the command first, and then Ctrl + Z in the background.

You cannot add &:

[email protected]:/var/www/html/doc$ sudo node server &

You must execute the command first:

[email protected]:/var/www/html/doc$ sudo node server
[sudo] password for XXX: enter password

Then pressctrl+zPut the program in the background to run

The reason is very simple, because you need to confirm the password after entering the command. You want to add it directly&If you let the program run in the background, isn’t it a big bug?
This is also a point that many tutorial articles on the internet ignore. They forget to remind readers who have just come into contact with Linux, which makes everyone take a lot of detours, such as me, ha ha ha.