03 Exec
03 Exec
1
exec(): Loading and Running
Programs
After fork, the child process is an identical
duplicate of the parent process
How do we start a new program, instead of
2
int execve( char *filename, char *argv[ ],
char *envp );
filename: name of the executable file to run
$HOME, etc.)
returns -1 if error, otherwise doesn’t return
3
int main() { /* exec2.c */
char *args[2];
args[0] = “/bin/echo”;
args[1] = NULL;
printf(“About to exec from process %d\n”, getpid());
sleep(1);
execv(“./exec2”, args);
printf(“Done exec-ing ...\n”);
return 0;
}
4
exec() does not create a new process!
Replaces the address space and CPU state of the current
process
Loads the address space from the executable file and starts it
from main()
On success, exec does not return!
5
execv(new_program, argv[ ])
Initial process
fork
fork() returns pid=0 and runs as a
Returns a cloned parent until execv is called
new PID
Original New
process new_Program
Copy of
Continues (replacement)
Parent
execv(new_program)
6
Exercise
Write a program that creates a child process,
the child executes /bin/ls, and then the parent
prints “done”. Make sure the word “done” is
printed after the output of ls.
7
int main() { /* exec3.c */
if (fork() == 0) { /* Child process */
char *args[2];
args[0] = “/bin/ls”; /* Not required!! */
args[1] = NULL; /* Indicate end of args array */
execv(“/bin/ls”, args);
exit(0); /* in case exec fails! */
}
wait(NULL);
printf(“Done\n”);
return 0;
}
8
Waiting for a Child Process
If a process (the parent) calls fork() to create a
process (the child), the parent doesn't automatically
wait for the child to finish. The parent must call
wait.
So if wait is not called, which process finishes first?
9
Zombies
If the parent finishes first, the child becomes an
orphan and is adopted by a system process called
init whose pid is 1.
If the child finishes first, it becomes a zombie.
10
Summary
Basic functions
fork spawns new processes
exit terminates own process
wait and waitpid wait for and reap terminated children
execve runs new program in existing process
11