一、行程
1、行程的定義
程式:程式是存放在存盤介質(例如磁盤)上的一個可執行檔案
行程:行程是程式執行的實體,包括程式計數器、暫存器和變數的當前值
2、行程的狀態及轉換
按生命周期劃分為三種狀態:
就緒態:行程已經具備執行的一切條件,等待CPU的時間片
執行態:行程正在占用CPU
等待態:行程因不具備某些執行條件而暫時無法繼續執行
行程的調度機制:
時間片輪轉,背景關系切換
行程的轉換

3、行程控制塊
作業系統是根據PCB(process control block)來對并發執行的行程進行控制和管理的,
系統在創建一個行程的時候會開辟一段記憶體空間存放與此行程相關的PCB資料結構
Linux中PCB存放在task_struct結構體中,可以在sched.h中查到該結構體
二、行程控制
1、行程號
每個行程都由一個行程號來標識,型別為pid_t,行程號的范圍是:0~32767
0號行程是調度行程,用于交換
1號行程是init行程,是所有行程的祖先
Linux系統中使用ps ajx可以查詢到行程的資訊,類似于Windows的任務管理器
主要引數有
PPID:父行程ID
PID:行程ID
PGID:行程組ID
COMMAND:行程名
Linux作業系統提供了3個獲得行程號的函式getpid()、getppid()、getpgid()
#include <sys/types.h>
#include <unistd.h>
包含這兩個頭檔案即可呼叫
pid_t getpid(void);
pid_t getppid(void);
pid_t getpgid(pid_t pid);
//案例演示
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
printf("pid = %d\n", getpid());
printf("ppid = %d\n", getppid());
printf("pgid = %d\n", getpgid(getpid()));
while (1)
;
return 0;
}
/*
運行結果:
pid = 7406
ppid = 7349
pgid = 7406
最后使用Ctrl+c 結束行程
*/
2、行程的創建(fork)
在Liunx下,創建行程的主要方法是呼叫以下兩個函式:
#include<sys/types.h>
#include<unistd.h>
pid_t fork(void);
pid_t vfork(void);
功能:
fork()函式用于從一個已存在的行程中創建一個新行程,新行程稱為子行程,原行程為父行程
回傳值:
成功:子行程中回傳0,父行程回傳子行程ID;失敗回傳-1,回傳值如何應用后續會介紹
使用fork函式得到的子行程是父行程的一個復制品,直接繼承整個父行程的地址空間(堆疊區堆區BSS區資料區代碼區),因此使用fork函式的的代價是很大的,
//行程的創建實體
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
//使用fork函式創建行程
fork();
printf("Hello World\n");
//結果會列印兩次Hello World,表明行程創建了,驗證后使用Ctrl+c終止行程
//因此需要注意,執行一次fork,就會在原有的行程中創建一個新行程,如果fork之后不進行區分父子行程,則后面的代碼都會執行
while (1)
;
return 0;
}
//那么如何進行父子行程的區分呢?通過回傳值,以下是實體驗證
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
pid_t pid;
pid = fork();
if (pid < 0)
{
perror("fail to fork!\n");
return -1;
}
else if (pid > 0) //父行程代碼區
{
while (1)
{
printf("父行程運行中\n");
sleep(1);
printf("*************\n");//此行代碼可用于驗證父子行程是交替運行的,誰先誰后是不確定的
}
}
else //子行程代碼區
{
while (1)
{
printf("子行程運行中\n");
sleep(1);
printf("--------------\n");
}
}
return 0;
}
//父子行程擁有獨立的地址空間
//子行程會復制父行程fork之前的所有內容
//但是fork之后,父子行程完全獨立,無論堆區、堆疊區、資料區如何改變,都不受對方影響;如果是對檔案操作的話,會受對方影響
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int gVar = 10;
int main(int argc, char const *argv[])
{
pid_t pid;
static int s_s32Var = 11;
int s32Var = 12;
pid = fork();
if (pid < 0)
{
perror("fail to fork!\n");
return -1;
}
else if (pid > 0) //父行程代碼區
{
printf("父行程運行中\n");
gVar++;
s_s32Var++;
s32Var++;
printf("gVar=%d,s_s32Var=%d,s32Var=%d\n", gVar, s_s32Var, s32Var);
}
else //子行程代碼區
{
sleep(1); //行程睡眠1s,讓父行程運行完畢
printf("子行程運行中\n");
printf("gVar=%d,s_s32Var=%d,s32Var=%d\n", gVar, s_s32Var, s32Var);
}
while (1)
;
return 0;
}
//子行程和父行程有一些公有區域,例如磁盤空間,內核空間
//檔案描述符的偏移量保存在內核空間中,所以父行程改變偏移量,則子行程獲取的偏移量是改變之后的
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char const *argv[])
{
int fd;
if ((fd = open("test.txt", O_RDONLY)) == -1) //test.txt內容自定義,建議50bits
{
perror("fail to open test.txt\n");
return -1;
}
pid_t pid;
pid = fork();
if (pid < 0)
{
perror("fail to fork!\n");
return -1;
}
else if (pid > 0) //父行程代碼區
{
printf("父行程運行中\n");
char buf[50] = "";
if (read(fd, buf, 32) == -1)
{
printf("fail to read\n");
return -1;
}
printf("buf = [ %s ]\n", buf);
}
else //子行程代碼區
{
sleep(1); //行程睡眠1s,讓父行程運行完畢
printf("子行程運行中\n");
char buf[50] = "";
//取消lseek的注釋就可以把偏移量設定為檔案開頭
//lseek(fd, 0, SEEK_SET);
if (read(fd, buf, 32) == -1)
{
printf("fail to read\n");
return -1;
}
printf("buf = [ %s ]\n", buf);
}
while (1)
;
return 0;
}
3、行程的掛起
行程在一定的時間內沒有任何動作,稱為行程的掛起(man 3 sleep)
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
功能:
行程掛起指定的秒數,直到指定的時間用完或收到信號才解除掛起,
回傳值:
若行程掛起到sec指定的時間則回傳0,若有信號中斷則回傳剩余秒數
行程掛起到指定秒數后,行程狀態切換到就緒態
4、行程的等待
父子行程有時候需要簡單的行程間同步,例如父行程等待子行程結束
Linux下提供了以下兩個等待函式wait()、waitpid()----使用man 2 wait查詢具體資訊
需要包含頭檔案
#include <sys/types.h>
#include <sys/wait.h>
wait函式:
pid_t wait(int *status);
功能: 等待子行程終止,如果子行程終止了,此函式會回收子行程的資源,
呼叫wait函式的行程會掛起,直到他的一個子行程退出或收到一個不能被忽視的信號時才被喚醒
若呼叫行程沒有子行程或它的子行程已經結束,該函式立即回傳
引數: 函式回傳時,引數status中包含子行程退出時的狀態資訊,
子行程的退出資訊在一個int中包含了多個欄位,用宏定義可以取出其中的每個欄位
回傳值: 如果執行成功則回傳子行程的行程號,
出錯回傳-1,失敗原因可以在errno中查找
取出子行程的退出資訊
WIFEXITED(status)
returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().
如果子行程是正常終止的,取出的欄位非零,子行程可以通過exit或者_exit函式發送退出狀態
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to
exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should be employed only if WIFEXITED returned true.
回傳子行程的退出狀態,退出狀態保存在status變數的8~16位,在用此宏前應先用宏WIFEXITED判斷子行程是否正常退出,正常退出才可以使用此宏
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
pid_t pid;
pid = fork();
if (pid < 0)
{
perror("fail to fork!\n");
return -1;
}
else if (pid > 0) //父行程代碼區
{
#if 0
wait(NULL); //等待子行程運行結束后再運行父行程
printf("進入父行程\n");
#endif
//如果通過接收子行程的退出狀態來執行父行程,子行程就要使用exit或_exit函式退出行程時發送退出狀態
int status, ret;
wait(&status);
ret = WIFEXITED(status);
printf("ret = %d \n", ret);
if (ret != 0) //子行程正常退出
{
printf("子行程回傳值:%d\n", WEXITSTATUS(status));
}
printf("父行程結束運行\n");
}
else //子行程代碼區
{
printf("進入子行程\n");
for (int i = 0; i < 2; i++)
{
printf("子行程運行中\n");
sleep(1);
}
}
return 0;
}
/*
waitpid函式(拓展了解,不要求掌握)
pid_t waitpid(pid_t pid, int *status, int options);
功能:
等待子行程終止,如果子行程終止了,此函式會回收子行程的資源
引數
pid的值:
pid>0:等待行程ID等于pid的子行程
pid=0:等待同一個行程組中的任何子行程,如果子行程已經加入了別的行程組,waitpid不會等待他
pid=-1:等待任一子行程,此時waitpid和wait作用一樣
pid<-1:等待指定行程組中的任何子行程,這個行程組的ID等于pid的絕對值
status引數中包含子行程退出時的狀態資訊
options引數能進一步控制waitpid的操作:
0--同wait,阻塞父行程,等待子行程退出,
WNOHANG--沒有任何已經結束的子行程,則立即回傳
WUNTRACED--如果子行程暫停了則此函式馬上回傳,并且不予以理會子行程的結束狀態
回傳值:
執行狀態改變了的子行程的ID;如果設定了WNOHANG且pid指定的行程存在則回傳0
出錯回傳-1,當pid所指示的子行程不存在,或此行程存在,但不是呼叫行程的子行程,waitpid就會出錯回傳,這時errno被設定為ECHILD
*/
5、行程的終止
僵尸行程(Zombie Process):
行程已經運行結束,但行程占用的資源未被回收,這樣的行程稱為僵尸行程
子行程已運行結束,父行程未呼叫wait函式回收子行程的資源是子行程變為僵尸行程的原因
孤兒行程(Orphan Process):
父行程運行結束,但子行程未運行結束的子行程
守護行程(Daemon Process):
守護行程是個特殊的孤兒行程,這種行程脫離中斷,在后臺運行
在Linux中,可以通過以下方式結束正在運行的行程:
void exit(int value);
void _exit(int value);
exit函式:
#include <stdlib.h>
void exit(int status);
status是回傳給父行程的引數
_exit函式:
#include <unistd.h>
void _exit(int status);
status也是回傳給父行程的引數
那么兩者有什么區別呢?
exit為庫函式,而_exit為系統呼叫
exit會重繪緩沖區,但是_exit不會重繪緩沖區
return 與exit、_exit的區別:
return在子函式中使用只能退出當前函式,無法終止行程
exit退出行程且可以重繪緩沖區
_exit僅退出行程
6、行程退出清理
行程在退出前可以用atexit函式注冊退出處理函式
#include <stdlib.h>
int atexit(void(*function)(void));
功能:行程結束時呼叫的行程退出執行注冊函式
引數function:行程結束前,呼叫函式的入口地址,一個行程中可以多次呼叫atexit函式注冊清理函式,正常結束前呼叫函式的順序和注冊時的順序相反,
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void clear1(void)
{
printf("clear1 func excute\n");
}
void clear2(void)
{
printf("clear2 func excute\n");
}
void clear3(void)
{
printf("clear3 func excute\n");
}
int main(int argc, char const *argv[])
{
//atexit函式在行程結束才會呼叫
//多個atexit函式進行呼叫,執行順序與呼叫順序相反
atexit(clear1);
atexit(clear2);
atexit(clear3);
printf("process sleep for 3 sec\n");
sleep(3);
return 0;
}
7、行程的創建–vfork函式
#include <sys/types.h>
#include <unistd.h>
pid_t vfork(void);
功能:vfork函式和fork函式一樣都是在已有的行程中創建一個新的行程,但它們創建的子行程是有區別的
回傳值:創建子行程成功,則在子行程中回傳0,父行程中回傳子行程ID,出錯回傳-1
fork函式和vfork函式的區別:
vfork保證子行程先運行,在它呼叫exec或exit之后,父行程才可能被調度運行,
vfork和fork一樣都創建一個子行程,但它并不將父行程的地址空間完全復制到子行程中,因為子行程會立即呼叫exec(或exit),于是就不訪問地址空間了
相反,在子行程中呼叫exec或exit之前,它在父行程的地址空間中運行,在exec之后子行程會有自己的行程空間,
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char const *argv[])
{
//使用vfork創建完子行程后,子行程會先執行,直到子行程運行exit或者exec后,父行程才會執行
pid_t pid;
pid = vfork();
if (pid < 0)
{
printf("fail to vfork\n");
exit(1);
}
if (pid == 0) //子行程
{
for (int i = 0; i < 2; i++)
{
printf("son process excute\n");
sleep(1);
}
exit(0);
}
else //父行程
{
printf("father process excute\n");
}
return 0;
}
//在子行程中呼叫exec或exit之前,它在父行程的地址空間中運行,在exec之后子行程會有自己的行程空間 這句話的驗證實體如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int gVar = 10;
int main(int argc, char const *argv[])
{
pid_t pid;
static int s_s32Var = 11;
int s32Var = 12;
pid = vfork();
if (pid < 0)
{
perror("fail to vfork!\n");
exit(1);
}
else if (pid == 0) //子行程代碼區
{
printf("子行程運行中\n");
gVar++;
s_s32Var++;
s32Var++;
printf("gVar=%d,s_s32Var=%d,s32Var=%d\n", gVar, s_s32Var, s32Var);
sleep(1);
exit(1);
}
else //父行程代碼區
{
printf("父行程運行中\n");
sleep(1);
printf("gVar=%d,s_s32Var=%d,s32Var=%d\n", gVar, s_s32Var, s32Var);
}
return 0;
}
8、行程的替換
行程的替換
exec函式族,是由六個exec函陣列成的
1、exec函式族提供了六種在行程中啟動另一個程式的方法
2、exec函式族可以根據指定的檔案名或目錄名找到可執行檔案
3、呼叫exec函式的行程并不創建新的行程,故呼叫exec前后,行程的行程號并不會改變,其執行的程式完全由新的程式替換,而新程式則從其main函式開始執行
exec函式族取代呼叫行程的資料段、代碼段和堆疊段
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ... /* (char *) NULL */);
int execlp(const char *file, const char *arg, .../* (char *) NULL */);
int execle(const char *path, const char *arg, .../*, (char *) NULL, char * const envp[] */);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);
六個函式中只有execvpe是真正意義上的系統呼叫,其他函式都是在此基礎上封裝的庫函式
l即list,引數地址串列,以空指標結尾
v即vector,存有各引數地址的指標陣列的地址
p即path,按PATH環境變數指定的目錄搜索可執行檔案
e即environment,存有環境變數字串地址的指標陣列的地址
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
int main(int argc, char const *argv[])
{
pid_t pid;
pid = fork();
if (pid < 0)
{
perror("fail to fork!\n");
exit(1);
}
else if (pid == 0) //子行程
{
printf("This is the child process!\n");
//whereis 命令可以查路徑
//不帶p的函式,命令的路徑一定要寫絕對路徑
#if 0
if (execl("/bin/ls", "ls", "-l", NULL) == -1)
{
printf("fail to execl\n");
exit(1);
}
#endif
#if 0
if (execlp("ls", "ls", "-al", NULL) == -1)
{
printf("fail to execlp\n");
exit(1);
}
#endif
#if 1
char *str[] = {"ls", "-l", NULL};
if (execv("/bin/ls", str) == -1)
{
printf("fail to execv!\n");
exit(1);
}
#endif
//除了shell命令外,引數還可以可執行檔案/shell腳本,這個試著自己寫一下,eg:execl("./hello", "./hello", NULL);
//用于驗證 exec函式族取代呼叫行程的資料段、代碼段和堆疊段
//當exec函式執行完畢后,當前行程就結束了,所以下面的HelloWorld列印不會出現
printf("Hello World\n");
}
else //父行程
{
printf("This is the parent process!\n");
wait(NULL);
printf("The child process has been quited!\n");
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/259327.html
標籤:其他
下一篇:ROS中的資訊訂閱
