wait系統(tǒng)調(diào)用會使父進程阻塞直到一個子進程結束或者是父進程接受到了一個信號.如果沒有父進程沒有子進程或者他的子進程已經(jīng)結束了wait回立即返回.成功時(因一個子進程結束)wait將返回子進程的ID,否則返回-1,并設置全局變量errno.stat_loc是子進程的退出狀態(tài).子進程調(diào)用exit,_exit 或者是return來設置這個值. 為了得到這個值Linux定義了幾個宏來測試這個返回值。
WIFEXITED:判斷子進程退出值是非0
WEXITSTATUS:判斷子進程的退出值(當子進程退出時非0).
WIFSIGNALED:子進程由于有沒有獲得的信號而退出.
WTERMSIG:子進程沒有獲得的信號號(在WIFSIGNALED為真時才有意義).
waitpid等待指定的子進程直到子進程返回.如果pid為正值則等待指定的進程(pid).如果為0則等待任何一個組ID和調(diào)用者的組ID相同的進程.為-1時等同于wait調(diào)用.小于-1時等待任何一個組ID等于pid絕對值的進程. stat_loc和wait的意義一樣. options可以決定父進程的狀態(tài).可以取兩個值 WNOHANG:父進程立即返回當沒有子進程存在時. WUNTACHED:當子進程結束時waitpid返回,但是子進程的退出狀態(tài)不可得到.父進程創(chuàng)建子進程后,子進程一般要執(zhí)行不同的程序.為了調(diào)用系統(tǒng)程序,我們可以使用系
統(tǒng)調(diào)用exec族調(diào)用.exec族調(diào)用有著5個函數(shù).
#include <unistd.h>
int execl(const char *path,const char *arg,...);
int execlp(const char *file,const char *arg,...);
int execle(const char *path,const char *arg,...);
int execv(const char *path,char *const argv[]);
int execvp(const char *file,char *const argv[]): |
exec族調(diào)用可以執(zhí)行給定程序.關于exec族調(diào)用的詳細解說可以參考系統(tǒng)手冊(man exec
下面我們來學習一個實例.注意編譯的時候要加 -lm以便連接數(shù)學函數(shù)庫.
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <math.h>
void main(void)
{
pid_t child;
int status;
printf("This will demostrate how to get child status ");
if((child=fork())==-1)
{
printf("Fork Error :%s ",strerror(errno));
exit(1);
}
else if(child==0)
{
int i;
printf("I am the child:%ld ",getpid());
for(i=0;i<1000000;i++) sin(i);
i=5;
printf("I exit with %d ",i);
exit(i);
}
while(((child=wait(&status))==-1)&(errno==EINTR));
if(child==-1)
printf("Wait Error:%s ",strerror(errno));
else if(!status)
printf("Child %ld terminated normally return status is zero ",
child);
else if(WIFEXITED(status))
printf("Child %ld terminated normally return status is %d ",
child,WEXITSTATUS(status));
else if(WIFSIGNALED(status))
printf("Child %ld terminated due to signal %d znot caught ",
child,WTERMSIG(status));
} |
strerror函數(shù)會返回一個指定的錯誤號的錯誤信息的字符串。