Running a New Program
Of course, we do not expect a single program to meet all our computing
requirements,
or for both parent and child to conveniently execute different paths through
the same code,
and so we need the ability to commence the execution of
new programs after a fork().
Under Unix/Linux, a new program may replace the currently running program.
The new
program runs as the same process (it has the same pid, confusing!),
by overwriting the current process's memory (instructions and data)
with the instructions and data of the new program.
The single system call execv()
requests the execution of a new program as the current process:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
char *program_arguments[] = {
"ls",
"-l",
"-F",
NULL
};
....
execv( "/bin/ls", program_arguments );
// A SUCCESSFUL CALL TO exec() DOES NOT RETURN
exit(EXIT_FAILURE); // IF WE GET HERE, THEN exec() HAS FAILED
|
On success, execv() does not return (to where would it return?)
On error, -1 is returned, and errno is set appropriately
(EACCES, ENOENT, ENOEXEC, ENOMEM, ....).
The single system call is supported by a number of library functions
(see man execl) which simplify the calling sequence.
Typically, the call to execv() (via one of its library interfaces)
will be made in a child process,
while the parent process continues its execution,
and eventually waits for the child to terminate.
CITS2002 Systems Programming, Lecture 9, p6, 19th August 2024.
|