1. 程式人生 > >Linux Guard Service - 前臺進程和後臺進程切換

Linux Guard Service - 前臺進程和後臺進程切換

command pthreads 2.6 其中 子進程 查看進程 前臺 gpo interrupt

把一個正在執行的程序放入後臺

[root@localhost 01]# Ctrl+Z

此使程序被移動到後臺,但不能繼續輸出(處於暫停態)

[root@localhost 01]# ./test1-1 
1552227
1552227
1552227
1552227
^Z
[1]+  已停止                  ./test1-1
[root@localhost 01]# 
[root@localhost 01]# 
[root@localhost 01]# jobs
[1]+  已停止                  ./test1-1

讓該後臺程序繼續在後臺運行

[root@localhost 01]# bg %1
[1]+ ./test1-1 &
1552227
[root@localhost 01]# 1552227
1552227
1552227
^C

列出後臺程序列表

[root@localhost 01]# jobs

顯示已經進入後臺的程序列表

[root@localhost 01]# jobs
[1]   已停止                  ./test1-1
[2]-  已停止                  ./test1-1
[3]+  已停止                  man jobs

其中+是倒數第一個後臺進程,-是倒數第二個後臺進程,前方是後臺進程的序號

[root@localhost 01]# jobs
[1]-  已停止                  ./test1-1
[2]+  已停止                  ./test1-2

將某個特定後臺程序切換到前臺

[root@localhost 01]# fg %n

其中n是jobs列表中的後臺進程序號

[root@localhost 01]# fg %1
./test1-1
1552227
1552227

查看父進程標識

[root@localhost 01]# ps f
   PID TTY      STAT   TIME COMMAND
 49561 pts/1    Ss     0:00 -bash
 49959 pts/1    T      0:00  \_ ./test1-1
 49960 pts/1    T      0:00  \_ ./test1-2
 49962 pts/1    R+     0:00  \_ ps f
  2496 tty1     Ss+    0:00 -bash

使用ps f以樹形顯示所有進程可以查看到test1-1 test1-2的父進程都是-bash

在新終端查看進程標識

[root@localhost ~]# ps f
   PID TTY      STAT   TIME COMMAND
 50060 pts/3    Ss     0:00 -bash
 50093 pts/3    R+     0:00  \_ ps f
 50010 pts/2    Ss+    0:00 -bash
 49561 pts/1    Ss+    0:00 -bash
 49959 pts/1    T      0:00  \_ ./test1-1
 49960 pts/1    T      0:00  \_ ./test1-2
  2496 tty1     Ss+    0:00 -bash

在新終端打開後test1-1和test1-2的父進程是pts/1 的-bash也就是舊終端,新終端的-bash是pts/3,此使用jobs沒有test1-1和test1-2了

按Ctrl+D時登出終端

[root@localhost 01]# 登出

顯示有停止的任務,再使用ps -ef查看列表,後臺任務依然存在
再按一次Ctrl+D,終端已經登出,切換到另一個終端查看

Last login: Sun Oct 15 18:26:48 2017 from 192.168.80.1
[root@localhost ~]# ps -ef | grep test
root      49959      1  0 18:27 ?        00:00:00 ./test1-1
該進程被init進程收養後繼續運行,稱孤兒進程

直接把程序放到後臺執行 &

[root@localhost 01]# ./test1-1 &

此使程序會自動在後臺繼續運行,並進行輸出

[root@localhost 01]# ./test1-1 &
[1] 49856
[root@localhost 01]# 1552227
1552227

保持後臺程序在終端結束後依然存在

使用守護進程讓進程不以終端為父進程

daemon(0,0);

ps -ef 中的狀態含義

D    不可中斷     Uninterruptible sleep (usually IO)
R    正在運行,或在隊列中的進程
S    處於休眠狀態
T    停止或被追蹤
Z    僵屍進程
W    進入內存交換(從內核2.6開始無效)
X    死掉的進程


<    高優先級
N    低優先級
L    有些頁被鎖進內存
s    包含子進程
+    位於後臺的進程組;
l    多線程,克隆線程  multi-threaded (using CLONE_THREAD, like NPTL pthreads do)

Linux Guard Service - 前臺進程和後臺進程切換