1. command & : 后台运行,你关掉终端会停止运行。
2. nohup command & : 后台运行,你关掉终端也会继续运行。
3. setsid command & : 后台运行,你关掉终端也会继续运行。
4. (command &) : 后台运行,你关掉终端也会继续运行。
一、bg、fg、jobs
Linux提供了fg和bg命令,让你轻松调度正在运行的任务。假设你发现前台运行的一个程序需要很长的时间,但是需要干其他的事情,你就可以用ctrl-z,挂起这个程序,然后可以看到系统提示,然后我们可以把程序调度到后台执行。
tail -f main.cpp
[1]+ Stopped tail -f main.cpp
把程序调度到后台执行:
bg 1
查看正在运行的程序:
jobs -l
[1]+ 17963 Running tail -f main.cpp &
把程序调度回前台执行:
fg 1
二、&(当前shell为父进程,shell退出后子进程立即退出)
显示当前shell的PID:echo $$
tail -f main.cpp &
jobs -l
[1]+ 17963 Running tail -f main.cpp &
三、nohup &(当前shell为父进程,shell退出后忽略hangup信号,并设置父进程为init)
nohup tail -f main.cpp & #一般会进行输出重定向,否则产生nohup.out文件。
jobs -l
[1]+ 17963 Running tail -f main.cpp &
四、setsid(init直接为父进程)
ps -ef | grep tail
root 22520 1 0 22:53 ? 00:00:00 tail -f main.cpp
root 22522 22495 0 22:53 pts/0 00:00:00 grep tail
五、(command &)(进程在subshell中执行,等价于setsid)
ps -ef | grep tail
root 22520 1 0 22:53 ? 00:00:00 tail -f main.cpp
root 22522 22495 0 22:53 pts/0 00:00:00 grep tail
六、python脚本或者shell脚本启动的后台进程
1、ctrl+c 脚本被杀死 第一个tail没被杀死 第二个tail被杀死
2、kill 脚本被杀死 第一个和第二个tail都没有被杀死
#!/bin/bash
tail -f main.cpp &
tail -f main.cpp
#!/usr/bin/bash
import os
os.system('tail -f main.cpp &')
os.system('tail -f main.cpp')