The fork, execv and wait Unix system calls

Note: type pid_t is an integer type. It is typically defined by
typedef int pid_t;

Note: You can find out much more detail about these commands by using the Unix manual. For example, to find out about fork, do

  man fork
To find out about wait, you will need to do
  man -s 2 wait
to ask for the description of wait in section 2 of the manual. There is a different wait in section 1, and that is not what you want.

Use the following includes.

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

pid_t fork(void)

fork() creates a new child process, a copy of the parent process (the process that performs the fork).

The fork call returns 0 to the child process and the process number (a positive integer) to the parent process.

Example:

      pid_t pid = fork();
    

int execv(const char* path, char *const argv[])

execv(path,argv) causes the current process to abandon the program that it is running and start running the program in file path. Parameter argv is the argument vector for the command, with a null pointer at the end. It is an array of null-terminated strings.

Normally, execv does not return, since the current program is thrown away, and another program is started instead. In the event of an error (such as file path not being found), execv will return. Any return of execv indicates an error.

Example: Cause the current program to be replaced by a program running command ls -l -F.

 
      char* argv[4];
      argv[0] = "ls";
      argv[1] = "-l";
      argv[2] = "-F";
      argv[3] = NULL;
      execv(argv[0], argv);
    

pid_t wait(int *status)

wait() waits for a child process of the current process to terminate. When one does, wait stores the termination status of the terminated child into variable status, and returns the process number of the terminated child process.

If status is NULL, then the status value will not be stored.

The waiting process does not loop waiting for a child process to terminate. It is put into a wait queue. The operating system will only awaken it when a child terminates. So the waiting process does not use the processor at all until it is ready to go.

There are feature checks that you can use to check the status. Here are some of them.

Here are a few signals. All signals are positive integers. Most can be caught by a process and handled in a way that it chooses. An uncaught signal is either ignored or causes immediate termination, depending on the signal.

Example:

     int status;
     pid_t tid = wait(&status);