Linux進程的管理 <一>擷取進程資訊函數
進程又稱任務,是一個動態使用系統資源、處於活動狀態的應用程式。
進程的管理由進程式控制制塊PCB、進程調度、中斷管理、任務隊列等組成,它是linux檔案系統、儲存管理、裝置管理和驅動程式的基礎。
進程式控制制塊PCB中包含了進程的所有資訊,主要包括進程PID、進程所佔有的記憶體地區、檔案描述符和進程環境等資訊。
他用task_struct的資料結構表示,存在於include/linux/sch.h
進程狀態及轉換
#define TASK_RUNNING 0 //運行狀態#define TASK_INTERRUPTIBLE 1 //等待狀態(可被中斷)#define TASK_UNINTERRUPTIBLE 2 //等待狀態(不可被中斷)#define TASK_STOPPED 4 //停止狀態#define TASK_ZOMBIE 8 //睡眠狀態#define TASK_DEAD 16 //僵死狀態
進程的基本操作,六大類:
1.擷取進程資訊函數:主要通過讀取進程式控制制塊PCB中的資訊。
(1)getpid()
功能:用來擷取目前進程的進程標識。
定義函數:pid_t getpid(void)
傳回值:返回當前進程的進程識別號。
標頭檔:#include <unistd.h>
(2)getppid()
功能:用來擷取目前進程的父進程標識。
定義函數:pid_t getppid(void)
傳回值:返回當前進程的父進程識別號。
標頭檔:#include <unistd.h>
(3)getpgid()
功能:用來獲得參數pid指令進程所屬於的組識別號,若參數為0,則返回當前進程的組識別碼。
定義函數:pid_t getpgid(pid_t pid)
傳回值:執行成功則返回正確的組識別碼,若有錯則返-1,錯誤原因存在於errno中。
標頭檔:#include <unistd.h>
(4)getpgrp()
功能:用來獲得目前進程所屬於的組識別號,等價於getpgid(0)。
定義函數:pid_t getpgrp(void)
傳回值:執行成功則返回正確的組識別碼。
標頭檔:#include <unistd.h>
(5)getpriotity(void)
功能:用來獲得進程,進程組和使用者的進程執行優先權。
定義函數:int getpriority(int which,int who)
參數含義:
which:
PRIO_PROCESS who為進程的識別碼
PRIO_PGRP who為進程的組識別碼
PRIO_USER who為使用者識別碼
傳回值:執行成功則返回當前進程的優先順序(-20--20),值越小優先順序越高。若出錯則返-1,原因在errno中。
標頭檔:#include <sys/resource.h>
簡單一實例:
[keven@localhost systemCall]$ cat -n get_process_information.c
#include <stdio.h>#include <unistd.h>#include <sys/resource.h> int main(/*int argc,char **argv*/){ printf("This process's pid is:%d",getpid()); printf("/nThis process's farther pid is:%d",getppid()); printf("/nThis process's group pid is:%d",getpgid(getpid())); printf("/nThis process's group pid is:%d",getpgrp()); printf("/nThis process's priority is:%d/n",getpriority(PRIO_PROCESS,getpid())); return 0;}
[keven@localhost systemCall]$ ./get_process_information
This process's pid is:6172
This process's farther pid is:5681
This process's group pid is:6172
This process's group pid is:6172
This process's priority is:0
[keven@localhost systemCall]$