學習以前必須瞭解基本的概念:算法
進程,線程,進程3種狀態,進程調度以及4種算法,進程同步,死鎖,記不清的找度娘。函數
獲取ID學習
#include<sys/types.h>命令行
#include<unistd.h>線程
獲取本進程ID:指針
pid_t getpid(void)進程
獲取父進程ID:get
pid_t getppid(void)同步
舉例:string
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(void)
{
printf("PID=%d\n",getpid());
printf("PID=%d\n",getppid());
return 0;
}
進程建立:
#include<unistd.h>
pid_t fork(void)
建立子進程;被調用一次,返回兩次,可能3種取值;
1.父進程中,返回子進程PID;
2.子進程中,返回0;
3.錯誤返回一個負值;
子進程的數據空間,堆棧空間都會從父進程一個copy,而不是共享。
-vfork
pid_t vfork(void)
區別:vfork子進程與父進程共享數據段。
vfork子進程先執行,父進程後執行。
fork次序不肯定;
exec函數族:
被執行的程序替換調用它的程序:
區別:
fork建立一個新進程,產生一個新PID;
exec啓動一個新程序,替換原有進程,PID不變。
#include<unistd.h>
int execl(const char*path,const char*arg1,...);
path:被執行的程序名
argn:命令行參數,含參數名,以空指針(NULL)結束
舉例:
#include<unistd.h>
main()
{
execl("/bin/ls","ls","-al","/etc/passwd",(char*)0);
}
#include<unistd.h>
int execp(const char*path,const char*arg1,...);
path:被執行的程序名(不含路徑,從path環境變量中查找)。
exmple:
execp("ls","ls","-al","/etc/passwd",(char*)0);
#include<unistd.h>
int execv(const char*path, char*const argv[]);
example:
#include<unistd.h>
main
{
char *argvl[]={"ls","-al","/etc/passwd",(char*)0};
execv("/bin/ls",argv);
}
#include<stdlib.h>
int system(const char*sring);
調用fork產生子進程,由子進程調用/bin/sh -c string來執行參數string所表明的命令。
e:
system("ls -al /etc/passwd");
進程等待:
#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int*status)
阻塞該進程,直到某個進程退出。