linux命令的前后台的理解有点绕,涉及bg,fg命令和CTRL-Z的暂停命令,网上的文章有的语焉不详,所以做了一个简单测试,方便自己的记忆:
| 步骤 | terminal 1做测试 | terminal 2 使用ps命令查状态 | |||
|---|---|---|---|---|---|
| 启动命令在后台运行 | [nisy@localhost Debug] ./test_process1 1>1.log 2>2.log & [1] 28176[nisy@localhost Debug] jobs [1]+ 运行中 ./test_process1 > 1.log 2> 2.log & | ||||
| 查询状态 | [nisy@localhost Debug]$ ps axuf | grep test nisy 28176 89.0 0.0 2296 744 pts/0 R 06:21 0:02 | _ ./test_process1 | ||
| fg切换到前台 | [nisy@localhost Debug]$ fg %1 ./test_process1 > 1.log 2> 2.log | ||||
| 查询状态 | nisy 28176 93.0 0.0 2296 728 pts/0 R+ 06:21 0:23 | _ ./test_process1 | |||
| CTRL-Z 来停止执行 | ^Z [1]+ 已停止 ./test_process1 > 1.log 2> 2.log [nisy@localhost Debug]$ jobs [1]+ 已停止 ./test_process1 > 1.log 2> 2.log | ||||
| 查询状态 | nisy 28176 79.5 0.0 2296 728 pts/0 T 06:21 0:27 | _ ./test_process1 | |||
| bg在后台运行 | [nisy@localhost Debug] jobs [1]+ 运行中 ./test_process1 > 1.log 2> 2.log & | ||||
| 查询状态 | nisy 28176 67.3 0.0 2296 728 pts/0 R 06:21 0:40 | _ ./test_process1 | |||
| 切换到前台并CTRL-C终止执行 | [nisy@localhost Debug] ^C [nisy@localhost Debug] | ||||
| 查询状态 | ps命令查不到./test_process1的执行 | ||||
总之:
使用& 需要把标准输出和错误输出分别用1> 和2> 重定向出去,如果命令有标准输出或者错误输出,就会导致无法进入后台;
bg 和fg切前后台并且 执行 程序,如果需要停止程序,切到前台后按CTRL-D;如果需要终止程序,切到前台后按CTRL-C ;