Skip to content

Process Control

Create process

#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
//Returns: 0 to child, PID of child to parent, −1 on error

Terminate process

#include <stdlib.h>
void exit(int status);
//

Reap child processes

  • When a process terminates for any reason, the kernel does not remove it from the system immediately. Instead, the process is kept around in a terminated state until it is reaped by its parent (by calling wait() related system calls)

  • When the parent reaps the terminated child, the kernel passes the child’s exit status to the parent and then discards the terminated process.

  • A terminated process that has not yet been reaped is called a zombie.

  • When a parent process terminates, the kernel arranges for the init process to become the adopted parent of any orphaned children. The init process, which has a PID of 1, is created by the kernel during system start-up, never terminates, and is the ancestor of every process.

  • If a parent process terminates without reaping its zombie children, then the kernel arranges for the init process to reap them.

  • In many applications where a parent creates child processes, it is useful for the parent to be able to monitor the children to find out when and how they terminate. This facility is provided by wait() and related system calls.

#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status)
// Return process ID of terminated child, or -1 on error
// errno = ECHILD if the process has no child
pid_t waitpid(pid_t pid, int *statusp, int options);
// Returns: PID of child if OK, 0 (if WNOHANG), or −1 on error

Loading and running programs

#include <unistd.h>
int execve(const char *filename, const char *argv[], const char *envp[]);
// Does not return if OK; returns −1 on error