Executing a new program in a forked process
In the previous recipe, we learned how to fork a process using the
fork() system call. In the recipe before that, we learned how to replace the program in a process with
execl(). In this recipe, we'll combine the two,
execl(), to execute a new program in a forked process. This is what happens every time we run a program in Bash. Bash forks itself and executes the program we typed in.
Knowing how to use
execl() enables you to write programs that start new programs. For example, you could write your own shell with this knowledge.
For this recipe, you'll need the
pstree tool, the GCC compiler, and the Make tool. You can find installation instructions for these programs in the Technical requirements section of this chapter.
How to do it…
In this recipe, we'll write a program that
forks() and executes a new program in the child process. Let's get started: