Linux進程控制
獲取pid
#include<sys/types.h>
#include<unistd.h>
pid_t getpdi(void) // 獲取本進程id
pdi_t getppid(vodi) //獲取父進程id, 及獲取創建子進程的進程id
進程創建
#include<unistd.h>
pid_t fork(void) // 創建子進程
// 調用一次返回兩次值
// 1. 父進程中,返回新創建的子進程的id
// 2. 在子進程中, 返回0
// 3. 如果出現錯誤,返回一個負值
#include<sys/types.h>
#include<unistd.h>
pid_t vfork(void); // 創建子進程
區別:1. fork: 子進程拷貝父進程的數據段
vfork: 子進程與父進程共享數據段
2. fork: 父,子進程的執行順序不確定vfork: 子進程先運行, 父進程後運行
#include<stdio.h>
#include<unistd.h>
int main()
{
pid_t id;
int i = 0;
id = fork(); // 替換爲vfork()比較其運行結果
i += 10;
printf("i = %d\n", i);
return 0;
}
進程等待
#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int *status); // 阻塞該進程,直到某個子進程退出
exec函數族
exec用被執行的程序替換調用它的程序
區別: fork 創建一個新的進程,產生一個新的PID
exec啓動一個新程序,替換原有的進程,因此進程的id不會改變