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. (Section 1 describes complete programs. What we want is a sytem call.)

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

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 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(v) waits for a child process of the current process to terminate. When one does, wait stores the termination status of the terminated child (the value returned by main) 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(s) at all until it is ready to go.

Example:

     pid_t tid = wait(NULL);