C語言wait()函數:結束(中斷)進程函數(常用)
頭文件:
1
|
#include <sys/types.h> #include <sys/wait.h> |
定義函數:
1
|
pid_t wait ( int * status); |
函數說明:wait()會暫時停止目前進程的執行, 直到有信號來到或子進程結束. 如果在調用wait()時子進程已經結束, 則wait()會立即返回子進程結束狀態值. 子進程的結束狀態值會由參數status 返回, 而子進程的進程識別碼也會一快返回. 如果不在意結束狀態值, 則參數 status 可以設成NULL. 子進程的結束狀態值請參考waitpid().
返回值:如果執行成功則返回子進程識別碼(PID), 如果有錯誤發生則返回-1. 失敗原因存于errno 中.
范例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> main() { pid_t pid; int status, i; if (fork() == 0) { printf ( "This is the child process. pid =%d\n" , getpid()); exit (5); } else { sleep(1); printf ( "This is the parent process, wait for child...\n" ; pid = wait(&status); i = WEXITSTATUS(status); printf ( "child's pid =%d . exit status=^d\n" , pid, i); } } |
執行:
1
2
3
|
This is the child process. pid=1501 This is the parent process, wait for child... child's pid =1501, exit status =5 |
C語言waitpid()函數:中斷(結束)進程函數(或等待子進程中斷)
頭文件:
1
|
#include <sys/types.h> #include <sys/wait.h> |
定義函數:
1
|
pid_t waitpid(pid_t pid, int * status, int options); |
函數說明:waitpid()會暫時停止目前進程的執行, 直到有信號來到或子進程結束. 如果在調用wait()時子進程已經結束, 則wait()會立即返回子進程結束狀態值. 子進程的結束狀態值會由參數status 返回, 而子進程的進程識別碼也會一快返回. 如果不在意結束狀態值, 則參數status 可以設成NULL. 參數pid 為欲等待的子進程識別碼, 其他數值意義如下:
1、pid<-1 等待進程組識別碼為pid 絕對值的任何子進程.
2、pid=-1 等待任何子進程, 相當于wait().
3、pid=0 等待進程組識別碼與目前進程相同的任何子進程.
4、pid>0 等待任何子進程識別碼為pid 的子進程.
參數option 可以為0 或下面的OR 組合:
WNOHANG:如果沒有任何已經結束的子進程則馬上返回, 不予以等待.
WUNTRACED:如果子進程進入暫停執行情況則馬上返回, 但結束狀態不予以理會. 子進程的結束狀態返回后存于status, 底下有幾個宏可判別結束情況
WIFEXITED(status):如果子進程正常結束則為非0 值.
WEXITSTATUS(status):取得子進程exit()返回的結束代碼, 一般會先用WIFEXITED 來判斷是否正常結束才能使用此宏.
WIFSIGNALED(status):如果子進程是因為信號而結束則此宏值為真
WTERMSIG(status):取得子進程因信號而中止的信號代碼, 一般會先用WIFSIGNALED 來判斷后才使用此宏.
WIFSTOPPED(status):如果子進程處于暫停執行情況則此宏值為真. 一般只有使用WUNTRACED時才會有此情況.
WSTOPSIG(status):取得引發子進程暫停的信號代碼, 一般會先用WIFSTOPPED 來判斷后才使用此宏.
返回值:如果執行成功則返回子進程識別碼(PID), 如果有錯誤發生則返回-1. 失敗原因存于errno 中.
范例:參考wait().