wait, waitpid, waitid

Header Files

#include <sys/types.h>
#include <sys/wait.h>

Function Prototype

pid_t wait(int *statloc)
pid_t waitpid(pid_t pid, int *statloc, int op)
pid_t waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options)

Function

parent process 會呼叫這兩個函式來等待 child process 的 termination status (blocking)

wait

會等待任意一個 child process 回傳

waitpid

會等待指定的 child process 回傳

  • pid == -1: wait for any child
  • pid > 0: wait for child with pid
  • pid == 0: wait for an child with same group id
  • pid < -1: wait for any child with group id == abs(pid)

waitid

相較於前兩個給予了更多選項(後面)

Options for waitpid

ConstantDescription
WCONTINUED原本 waitpid 只有在 child process terminate 時才會回傳, 使用這個 option 後,當 child process 從 stopped 狀態恢復執行時也會回傳
WNOHANG把 waitpid 變成 non-blocking,如果 child process 還沒有結束,回直接回傳而不會 block
WUNTRACED原本 waitpid 只有在 child process terminate 時才會回傳, 使用這個 option 後,當 child process 被停止(stopped)時也會回傳

waitid

idtype

P_PID

wait 特定的 process (id指定)

P_PGID

wait 特定 group 中的 process (id指定)

P_ALL

等待任何 child process (id會被忽略)

options

waitpid 類似,沒有 WUNTRACED但多了

ConstantDescription
WEXITEDbehavior 就和沒有設 option 的 waitpid 相同
WSTOPPED只等待 stopped 而不是 terminated 的 process
WNOWAIT可以偷看而不消耗狀態,當我們用之前的方式查看時,這個狀態會被消耗,但用了這個 option,之後我們就可以再次用wait, waitpid, waitid 之類的取得相同的狀態