用到的函數的功能主要有擷取進程id、建立進程、進程退出、進程等待、執行程式。
擷取進程id:getpid(),getppid()
建立進程:fork(),vfork()
進程退出:exit()
進程等待:wait()
執行程式:exec(),system() getpid函數
原型:pid_t getpid(void)標頭檔:<unistd.h><sys/types.h>功能:返回調用該函數的進程id,且該函數總是運行成功
getppid函數
原型:pid_t getppid(void)標頭檔:<unistd.h><sys/types.h>功能:返回調用該函數的進程的父進程id,且該函數總是運行成功
fork函數
原型:pid_t fork(void)標頭檔:<unistd.h>功能:建立一個子進程。成功則在父進程返回子進程PID,在子進程返回0;失敗返回-1.#include<stdio.h>#include<unistd.h>#include<stdlib.h>void main(){ pid_t pid; pid=fork(); if(pid==0) { printf("this is child program,the return is %d\n",pid); } else { printf("this is father program,the return is %d\n",pid); } exit(0);}
使用fork函數後,父進程就會產生一個子進程,並且父進程和子進程都會執行fork函數後的代碼,直至退出進程。由於在父進程返回子進程PID,在子進程返回0,因此可利用該傳回值,讓父進程和子進程執行不同功能。子進程列印“this is child program,the return is 0”在shell提示符後面的原因為先執行父進程,執行完父進程後作業系統彈出shell提示符,然後在執行子進程。 vfork函數
原型:pid_t vfork(void)標頭檔:<unistd.h><sys/types.h>功能:建立一個子進程,並阻塞父進程。成功則在父進程返回子進程PID,在子進程返回0;失敗返回-1.#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<stdlib.h>void main(){ pid_t pid; pid=vfork(); if(pid==0) { printf("this is child program,the return is %d\n",pid); } else { printf("this is father program,the return is %d\n",pid); } exit(0);}
先執行子進程,再執行父進程。
fork函數與vfork函數都用於建立子進程,但兩者區別有兩點:
① fork:子進程擁有獨立的資料區段,堆棧。
vfork:子進程與父進程共用資料區段,堆棧。
② fork:父、子進程的執行次序不確定
vfork:子進程先運行,父進程後運行
父進程可採用return或者exit()函數退出進程; 子進程只能採用exit()函數退出進程,其中exit(0)表示正常退出,exit(1)表示異常退出
wait函數
原型:pid_t wait(int *status)標頭檔:<sys/wait.h><sys/types.h>功能:掛起調用它的進程,直到該進程的一個子進程結束。成功則返回結束的那個子進程的ID,失敗返回-1參數:status若不為NULL,則用於記錄子進程的退出狀態
執行進程的函數為exec,exec是一個函數族,共有6個:execl,execv,execle,execve,execlp,execvp,以execl為例進行說明 execl函數
原型:int execl(const char* pathname,const char* arg,...)標頭檔:<unistd.h>功能:運行可執行檔,並且原進程的代碼不再執行,只執行新的代碼。成功時不返回,失敗時返回-1.參數:pathname為要啟動並執行可執行檔的路徑 arg及後面的參數作為可執行檔的參數,並以一個NULL作為參數的結束標誌。#include<stdio.h>#include<unistd.h>#include<stdlib.h>#include<sys/types.h>#include<sys/wait.h>void main(){ pid_t pid; pid=fork(); if(pid==0) { execl("/bin/ls","ls","/home",NULL); printf("this is child program,the return is %d\n",pid); } else { wait(NULL); printf("this is father program,the return is %d\n",pid); } exit(0);}
由上可看出,使用execl函數後,原進程代碼不再執行,轉為執行新的代碼。
fork建立一個新的進程,產生一個新的PID。
exec保留原有的進程,執行新的代碼。 system函數
原型:int system(const char* command)標頭檔:<stdlib.h>功能:執行一條shell指令,該函數會產生子進程