Process Control

fork()

Creates a new child process by duplicating the calling (parent) process.

1pid_t fork(void);

Return Value:

  • Parent: child’s PID (positive)
  • Child: 0
  • Error: -1

Example:

1pid_t pid = fork();
2if (pid == 0) {
3    printf("Child process\n");
4    _exit(0);
5} else {
6    printf("Parent process, child PID: %d\n", pid);
7}

wait()

Suspends execution of the calling process until any of its child processes terminates.

1pid_t wait(int *status);

Return Value:

  • Success: PID of terminated child
  • Error: -1

Example:

1int status;
2wait(&status);

waitpid()

Waits for a specific child process or set of children to terminate.

1pid_t waitpid(pid_t pid, int *status, int options);

Return Value:

  • Success: PID of child
  • Error: -1
  • With WNOHANG and no children ready: 0

Example:

1int status;
2pid_t child = fork();
3if (child == 0) _exit(5);
4waitpid(child, &status, 0);

exit()

Terminates the calling process and performs cleanup (e.g., flushes stdio buffers).

1void exit(int status);

Return Value:

  • Does not return

Example:

1exit(0);

_exit()

Immediately terminates the process without flushing stdio buffers or calling cleanup handlers.

1void _exit(int status);

Return Value:

  • Does not return

Example:

1_exit(0);

MACROS

WIFEXITED

Returns true if the child terminated normally (via exit() or _exit()).

1WIFEXITED(status)

Return Value:

  • True if child terminated normally

Example:

1int status;
2wait(&status);
3if (WIFEXITED(status)) {
4    printf("Child exited normally\n");
5}

WEXITSTATUS

Returns the exit status code of the child (only valid if WIFEXITED(status) is true).

1WEXITSTATUS(status)

Return Value:

  • Return code when WIFEXITED is true

Example:

1if (WIFEXITED(status)) {
2    int code = WEXITSTATUS(status);
3    printf("Exit code: %d\n", code);
4}

WIFSIGNALED

Returns true if the child terminated due to an uncaught signal.

1WIFSIGNALED(status)

Return Value:

  • True if child terminated by signal

Example:

1if (WIFSIGNALED(status)) {
2    printf("Child killed by signal\n");
3}
Last updated on