擷取進程ID
#include <sys/types.h>#include <unistd.h>pid_t getpid(void)//擷取本進程IDpid_t getppid(void)//擷取父進程ID
建立子進程
#include<unistd.h>pid_t fork(void)//功能:建立子進程//fork調用一次,卻返回兩次,有三種不同的傳回值//1.父進程中,fork返回新建立的子進程的PID//2.子進程中,fork返回0//3.如果出現錯誤,fork返回一個負值//注意:使用此函數建立的子進程,其資料空間、堆棧空間都會//從父進程得到一個拷貝,而不是共用
#include <sys/types.h>#include <unistd.h>pid_t vfork(void)//功能:建立子進程
vfork和fork建立子進程的區別:
- fork: 子進程拷貝父進程的資料區段
- vfork: 子進程與父進程共用資料區段
- fork: 父、子進程的執行次序不確定
- vfork: 子進程先運行,父進程後運行
exec函數族
exec用被執行的程式替換調用它的程式。
與fork區別:fork建立一個新的進程,產生一個新的PID,exec啟動一個新程式,替換原有的進程,因此進程的PID不會改變。
execl
#include <unistd.h>int execl(const char *path, const char *arg1,...)//參數說明://path:被執行的程式名(含完整路徑)//arg1-argn:被執行程式所需的命令列參數,含程式名。以null 指標(NULL)結束
execlp
#include <unistd.h>int execlp(const char *path, const char *arg1,...)//參數說明://path:被執行程式名(不含路徑,將從path環境變數中尋找該程式)//arg1-argn:被執行程式所需的命令列參數,含程式名。以null 指標(NULL)結束
execv
#include <unistd.h>int execv(const char *path, char *const argv[])//參數說明://path:被執行程式名(含完整路徑)//argv[]:被執行程式所需的命令列參數數組
system
#include <stdlib.h>int system(const char *string)//功能://調用fork產生子進程,由子進程調用/bin/sh -c string來執行參數string所代表的命令
進程等待
#include <sys/types.h>#include <sys/wait.h>pid_t wait(int *status)//功能:阻塞該進程,直到某個子進程退出