Chapter 9 Linux的程序管理 (Process management)
◎What is
Process
UNIX中Pocess代表一個具有獨立記憶空間、可單獨運作的”工作程式”(Program),每一件系統或User的工作均由各種不同的process完成之
◎Why Process
UNIX中,很多resource的管理,必須藉由process的控制來完成
◎Process ID
UNIX每一個程序都有一個唯一的識別代號,我們稱之為程序代號(process id or pid)
◎How Process
Works
每一process在必要情況之下由其Parent
Process產生,完成工作之後會自動釋放所有佔用的系統資源,結束並離開系統。
Process的產生 |
fork-and-exec是UNIX中所有process運作的模式。系統bootup的時候,第一個被執行的process(程式),其pid為1;經由fork-and-exec程序,啟動各個必要的process,而形成一個功能完整的作業系統。
±
fork是UNIX一個系統呼叫(system call),process fork時,會複製一個跟自己完全一模一樣的process (with different pid),並利用系統呼叫完成之傳回值,來區分parent process 與child process,而分別賦予child process不同的功能。
process於程式執行過程中,利用exec執行另一不同的程式,這個程式並且會完全取代原有程式(with the same pid)。
Process的結束
process及child process。
如果因某些原因,parent process在其結束前即已不存在,此 process即成為所謂的Zombie process(or defunct process),無法正常結束。
Child process通常會隨著parent process結束而結束,因此手動結束process “init”(系統第一個啟動的process, pid為1),將會造成系統當機。(目前大部分的UNIX作業系統會禁止你手動停止init的執行)
◎Process的管理相關指令
1. Monitor Proces with Command : ps
You can always monitor process information
currently running in the system, which including: process owner , CPU usage
, memory(real & virtual) usage, command name, PID(Process ID) etc.
Monitor Process whith "ps"
[root@nmc ~]#
ps
[root@nmc ~]# ps aux | more
[root@nmc ~]# ps aux --sort:pid | more
|
ps
各欄位意義
USER: Username of the
process owner
PID:
Process ID
%CPU: CPU time/elapsed
time
%MEM: Fraction of system
memory consumed
SIZE: Virtural memory used
(K)
RSS: Real memory used
TTY: Terminal port
associated with process
STAT: Process state
R Running
S Sleeping
I Idle
Z Zombie
START: Time or date
process started
TIME: Total CPU time used
COMMAND: Command line
being executed
程式名稱最後一個字是 d 者, 表示是 daemon 伺服程式. 如
inetd, httpd, nfsd, named
2. pstree -- 顯示執行程序的樹狀結構
指令對程序名稱相同者會自動合併, "|-httpd---3*[httpd]" 表示有 3 個 httpd 程序在系統中。
3. kill pid -- 結束 Process 的執行
PID | TTY | TIME | CMD |
19325 | pts/0 | 00:00:00 | login |
19413 | pts/0 | 00:00:00 | su |
19414 | pts/0 | 00:00:00 | tcsh |
19442 | pts/0 | 00:00:00 | ps |
19443 | pts/0 | 00:00:00 | awk |
[root@test /root]#
kill 19443
◎背景執行程式
程式執行不一定要在螢幕前進行,可以用背景程式管理的指令來達成目的,如 &, bg, fg, jobs等.
1. &
語法: [root@test/root]# command &
Example: [root @test /root]#find / -name test & <==將該執行程序丟到背景執行
2. jobs
說明: 使用 jobs 就可以知道背景中執行的工作項目有那些.
Example: [root @test /root]#jobs
[1]+ Stopped find / -name test & <==顯示有一個工作在背景下,狀態為停止。3. fg
說明:將背景中的指令移到螢幕前來動作
Example: [root @test /root]# jobs
[1]- Running find / -name test &
[2]+ Stopped vi test
[root @test /root]# fg %14. bg
說明:將背景中的程式由 stopped 變成 Running
Example: [root @test /root]#jobs
[1]- Stopped find / -name test &
[root @test /root]# bg %1
[root @test /root]# jobs
[1]- Running find / -name test &