Skip to content
On this page

wait(2)


标签:linux/api  

wait()

阻塞回收僵尸子进程。

c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>

int
main(int argc, char const* argv[])
{
  pid_t pid;
  pid_t zom_pid;

  pid = fork();
  if (pid < 0) {
    perror("fork()");
    return -1;
  } else if (pid == 0) {
    printf("child is running...\n");
    while (1)
      ;
  } else if (pid > 0) {
    printf("parent is running...\n");
    zom_pid = wait(NULL);
    printf("zom_pid = %d\n", zom_pid);
    while (1)
      ;
  }
  return 0;
}

上面这个程序用 kill 杀死子进程后,子进程不会变成僵尸进程,但是父进程会被wait函数阻塞。

函数原型

c
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *wstatus);

参数

wstatus: 用来检测线程退出原因的数值,因为需要修改,所以传入的是地址。如果不需要这个修改可以传入NULL

可以通过一系列宏函数检测退出的原因。

waitpid()

wait 不指定 pid,默认是回收任意一个 zombie 线程。

waitwaitpid(-1, &status, 0) 等价。

函数原型

`

c
pid_t waitpid(pid_t pid, int *status, int option);

参数

@pid:

  • <-1 : 等待是 pid 绝对值的所有进程
  • -1 : 等待所有的
  • 0: 等待和父进程的子进程
  • > 0: 等待指定 pid 的进程的状态改变

@statsu: 同 wait

@options:

  • WNOHANG: 立即返回 ( 非阻塞, 利用轮询检测子进程状态 )
  • WUNTRACED: also return if a child has stopped (but not traced via ptrace(2)). Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED (since Linux 2.6.10) also return if a stopped child has been resumed by delivery of SIGCONT.

退出值判断宏函数

这个结束状态通过宏函数进行判定:

txt
WIFEXITED(wstatus)
returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().

WEXITSTATUS(wstatus)
returns  the  exit status of the child.  This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return  statement  in  main().   This  macro should be employed only if WIFEXITED returned true.

WIFSIGNALED(wstatus)
returns true if the child process was terminated by a signal.

WTERMSIG(wstatus)
returns  the  number  of the signal that caused the child process to terminate.  This macro should be employed only if WIFSIGNALED returned true.

WCOREDUMP(wstatus)
returns true if the child produced a core dump (see core(5)).  This macro should be employed only if  WIFSIGNALED  returned true.

This  macro  is  not  specified  in POSIX.1-2001 and is not available on some UNIX implementations (e.g., AIX, SunOS). Therefore, enclose its use inside #ifdef WCOREDUMP ... #endif.

WIFSTOPPED(wstatus)
returns true if the child process was stopped by delivery of a signal; this is possible only if the call was done  using WUNTRACED or when the child is being traced (see ptrace(2)).

WSTOPSIG(wstatus)
returns the number of the signal which caused the child to stop.  This macro should be employed only if WIFSTOPPED returned true.

WIFCONTINUED(wstatus)
(since Linux 2.6.10) returns true if the child process was resumed by delivery of SIGCONT.

wait(3)/wait(4)

FreeBSD 的方言。

Last updated: