Linux 如何将任务进行前后台切换操作?

著名奶茶鉴定家 2021-08-12 15:33:56 浏览数 (2974)
反馈

Linux 是一个多任务的操作系统, 在同一时间,系统可以运行多个任务。

当我们使用Node或者Flask运行一个进程时, 该进程会占用终端。

例如:

# python cutword.py 
 * Serving Flask app 'cutword' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://10.150.39.18:7776/ (Press CTRL+C to quit)

将进程在后台运行

我们可以在命令后加上 & 符号,将进程切换到后台。

例如:

# nohup python cutword.py >/dev/null 2>&1 &
[1] 30979

nohup​ 的用途是不挂断地运行命令。

无论是否将 nohup 命令的输出重定向到终端,输出都将附加到当前目录的 nohup.out 文件中。

如果让程序始终在后台执行,即使关闭当前的终端也执行(​&​做不到),这时候需要​nohup​。该命令可以在你退出帐户/关闭终端之后继续运行相应的进程。

>/dev/null 2>&1​ 是将标准输出和错误输出都忽略。

​最后的&​将进程在后台运行。

[1] 30979​ 分别表示后台任务编号和进程ID。

查看后台任务

我们可以使用​jobs​命令查看在后台运行的进程列表信息。

# jobs
[1]+  运行中               nohup python cutword.py > /dev/null 2>&1 &

当终端关闭后,在另一个终端jobs是无法看到后台任务列表的,此时利用ps(进程查看命令)

# ps -aux | grep "cutword.py"

将进程切换到前台

我们可以使用 ​fg %后台编号​ 将指定进程切回前台运行。

# fg %1
nohup python cutword.py > /dev/null 2>&1

我们会发现,这时程序会一直卡在终端。这时,我们可以使用 ctrl+z 将它再次切到后台运行。

# fg %1
nohup python cutword.py > /dev/null 2>&1
^Z
[1]+  已停止               nohup python cutword.py > /dev/null 2>&1

但是,我们会发现,进程变成了 stopped 的状态,我们也可以在后台进程列表里看到它的状态。

这也是 ctrl+z 命令的特点:将进程切换到后台,并停止运行。

如果我们想让它恢复运行,我们就可以使用 bg 命令了。

# bg %1
[1]+ nohup python cutword.py > /dev/null 2>&1 &

终止后台任务

如果我们想杀死某个后台进程,我们可以使用 kill 命令。

kill 命令的用法有两种:

kill pid
kill %N

例如,我们想杀死后台编号为1的进程,可以这样:

# kill %1
# jobs
[1]+  已终止               nohup python cutword.py > /dev/null 2>&1

总结

命令 & ​:将任务进程在后台运行。

jobs​:查看后台的进程列表。

fg %后台任务编号​:将指定后台任务切换到前台运行。

bg %后台任务编号​: 恢复运行后台指定的任务。

kill %后台任务编号​:杀死后台指定任务。


0 人点赞