1.進程的概念
- 概念
程序是指編譯過的可執行的二進制代碼,再大點可以叫應用。進程是指正在運行的程序,一個程序可以有多個進程,一個進程中可以有多個線程。
輸入命令 top可以看到pid一直在刷新
2,進程ID
-
概念
每一個進程都有一個唯一的標識符,進程 ID 簡稱 pid。
進程的 ID 在一個固定的時刻是唯一的,需要注意的是,假如你在 s 秒的時候有一個進程 ID
是 1000,在另外一個時刻 s+n,另一個進程 ID 也有可能是 1000。
另外內核運行的第一個進程是 1,也就是內核的 init 程序,這個是唯一的。
進程 id 一般默認的最大值爲 32768,不過也是可以修改的,當然一般情況下不需要這麼做。
如果當前進程是 1000,那麼下一個分配的進程就是 1001,它是嚴格線性分配的。直到 pid 到
了最大值,才重新分配已經用過的進程 ID,當然這些進程都是已經死亡的進程。
除了 init 進程,其它進程都是由其它進程創立的。創立新進程的進程叫父進程,新進程叫
子進程。 -
函數
pid_t getpid(void); 參數:無。 返回值:成功返回進程號。
pid_t getppid(void); 參數:無。 返回值:成功返回父進程。
-
實驗例程
#include <stdio.h> #include <sys/types.h> #include <unistd.h> void main() { pid_t idp,id; idp = getppid(); printf("ppid = %d\n",idp); id = getpid(); printf("pid = %d\n",id); }
-
在ubuntu下編譯,加載到開發板運行
可以看到當前進程號和父進程號 -
進程有兩個命令,ps和kill分別是查看和終止進程
3.exex函數族 - 執行新程序
- 介紹
在 linux 中,exec 函數族是把程序直接載入內存,而不是在一個程序中運行多個進程。exec 函數族調用成功之後,會在內存中執行一個新的程序。在 linux 中要運行多任務需要使用 exec 函數族和 fork 進程。 - 有六個exec函數
首先函數族都是以 exec+xx 的方式命名的。
“l”和“v”表示參數是以列表還是以數組的方式提供的。
“p”表示這個函數的第一個參數是*path,就是以絕對路徑來提供程序的路徑,也可以以
當前目錄作爲目標。
“e”表示爲程序提供新的環境變量。 - 例程
execl.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <unistd.h>
//exec函數族
int main(void)
{
if(execl("/mnt/udisk/helloexec","helloexec","execl",NULL) == -1){
perror("execl error");
exit(1);
}
//程序已經跳轉走,如果正常execl不反回錯誤,下面的代碼不會執行!
printf("execl error!\n");
return 0;
}
helloexex.c
#include <stdio.h>
int main(int arc,char *argv[])
{
printf("Hello %s!\n",argv[1]);
}
- 在ubuntu下編譯,加載到開發板運行
4.fork 創建新進程
- 在 linux 中可以使用 fork 創建和當前進程一樣的進程,新的進程叫子進程,原來的進程叫
父進程。 - pid_t fork(void);
參數:無
返回值:執行成功,子進程 pid 返回給父進程,0 返回給子進程;出現錯誤-1,返回給父
進程。 - 例程
#include <stdio.h>
#include <unistd.h>
main()
{
pid_t pid;
int i=100;
pid = fork();
//調用出錯
if(pid == -1){
printf("fork failed\n");
return 1;
}
//返回給父進程子進程號,返回值大於0
else if(pid){
i++;
printf("\nThe father i = %d\n",i);
printf("The father return value is %d\n",pid);
printf("The father pid is %d\n",getpid());
printf("The father ppid is %d\n",getppid());
while(1);
}
//返回子進程0,返回值等於0返回給子進程
else{
i++;
printf("\nThe child i = %d\n",i);
printf("The child return value is %d\n",pid);
printf("The child pid is %d\n",getpid());
printf("The child ppid is %d\n",getppid());
while(1);
}
return 0;
}
5.進程終止 exit
- 在 main 函數的結尾會使用 return 或者exit 結束程序。當使用 exit 的時候,就是使用的進程終止函數 exit。
- void exit(int status)
參數:返回給父進程的參數。
返回值:無