wait

wait

#include <sys/wait.h>

pid_t wait(int *statloc);
pid_t waitpid(pid_t pid, int *statloc, int options);

The differences between these two functions are as follows:

  • The wait function can block the caller until a child process terminates, whereas waitpid has an option that prevents it from blocking.
  • The waitpid function doesn’t wait for the child that terminates first; it has a number of options that control which process it waits for.

waitpid

A typical demo code of waitpid.

#include "apue.h"
#include <sys/wait.h>

int
mai() {
    pid_t pid;

    pid = fork();

    if (pid < 0) {
        err_sys("fork failed");
        exit(1);
    }

    if (pid == 0) {
        printf("child process running\n");
        sleep(1);
        exit(0);
    }



    printf("parent process running\n");
    //If don't call waitpid, the child will be zombie process.
    waitpid(pid, NULL, 0); 
    for (; ;) {
        sleep(5);
    }

    exit(0);

}

The interpretation of the pid argument for waitpid depends on its value:

  • pid == − 1 Waits for any child process. In this respect, waitpid is equivalent to wait .

  • pid > 0 Waits for the child whose process ID equals pid .

  • pid == 0 Waits for any child whose process group ID equals that of the calling process.

  • pid < − 1 Waits for any child whose process group ID equals the absolute value of pid .

The waitpid function provides three features that aren’t provided by the wait function.

  1. The waitpid function lets us wait for one particular process, whereas the wait function returns the status of any terminated child.
  2. The waitpid function provides a nonblocking version of wait . There are times when we want to fetch a child’s status, but we don’t want to block.

  3. The waitpid function provides support for job control with the WUNTRACED and WCONTINUED options.

waitid

The waitid function is similar to waitpid , but provides extra flexibility.

#include <sys/wait.h>


int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);

Like waitpid , waitid allows a process to specify which children to wait for. Instead of encoding this information in a single argument combined with the process ID or process group ID, two separate arguments are used. The id parameter is interpreted base on the value of idtype.

wait3, wait4

The only feature provided by these two functions that isn’t provided by the wait , waitid , and waitpid functions is an additional argument that allows the kernel to return a summary of the resources used by the terminated process and all its child processes.

#include <sys/types.h>

#include <sys/wait.h>

#include <sys/time.h>

#include <sys/resource.h>


pid_t wait3(int *statloc, int options, struct rusage *rusage);
pid_t wait4(pid_t pid, int *statloc, int options, struct rusage *rusage);

results matching ""

    No results matching ""