
行程管理
|
167
舉例來說,假設你的程式想要取得特定子行程(pid 1742)的傳回值。但是,如果子行
程尚未終止,則立即返回。你可以使用如下的程式碼來完成此事:
int status;
pid_t pid;
pid = waitpid (1742, &status, WNOHANG);
if (pid ==
−
1)
perror ("waitpid");
else {
printf ("pid=%d\n", pid);
if (WIFEXITED (status))
printf ("Normal termination with exit status=%d\n",
WEXITSTATUS (status));
if (WIFSIGNALED (status))
printf ("Killed by signal=%d%s\n",
WTERMSIG (status),
WCOREDUMP (status) ? " (dumped core)" : "");
}
最後,請注意,如下的
wait()
用法:
wait (&status);
等效於如下的
waitpid()
用法:
waitpid (-1, &status, 0);
以更靈活的方式等待
在「等待子行程」功能上需要更大靈活度的應用程式,可以使用 POSIX 之 XSI 擴充所
定義(以及 Linux 所提供)的
waitid()
:
#include <sys/wait.h>
int waitid (idtype_t idtype,
id_t id,