C Tutorial: Playing with processes
Spawning a new program with fork + exec
The fork system call creates a new process. The execve system call overwrites a process with a new program. Like peanut butter and chocolate in the ever-delicious Reese's Peanut Butter Cups, these two system calls go together to spawn a new running program. A process forks itself and the child process execs a new program, which overlays the one in the current process.
Because the child process is initially running the same code that the parent was and has the same open files and the same data in memory, this scheme provides a way for the child to tweak the environment, if necessary, before calling the execve system call. A common thing to do is for the child to change its standard input or standard output (file descriptors 0 and 1, respectively) and then exec the new program. That program will then read from and write to the new sources.
Example
This is a program that forks itself and has the chiled exec the ls program, running the "ls -aF /" command. Five seconds later, the parent prints a message saying, I'm still here!. We use the sleep library function to put the process to sleep for five seconds.
Save this file by control-clicking or right clicking the download link and then saving it as forkexec.c.
Compile this program via:
If you don't have gcc, You may need to substitute the gcc command with cc or another name of your compiler.
Run the program: