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.


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.

/* forkexec: create a new process. */ /* The child runs "ls -aF /". The parent wakes up after 5 seconds */ /* Paul Krzyzanowski */ #include <stdlib.h> /* needed to define exit() */ #include <unistd.h> /* needed for fork() and getpid() */ #include <stdio.h> /* needed for printf() */ int main(int argc, char **argv) { void runit(void); int pid; /* process ID */ switch (pid = fork()) { case 0: /* a fork returns 0 to the child */ runit(); break; default: /* a fork returns a pid to the parent */ sleep(5); /* sleep for 5 seconds */ printf("I'm still here!\n"); break; case -1: /* something went wrong */ perror("fork"); exit(1); } exit(0); } void runit(void) { printf("About to run ls\n"); execlp("ls", "ls", "-aF", "/", (char*)0); perror("execlp"); /* if we get here, execlp failed */ exit(1); }

Download this file

Save this file by control-clicking or right clicking the download link and then saving it as forkexec.c.

Compile this program via:

gcc -o forkexec forkexec.c

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:



The Practice of Programming


The C Programming Language


The UNIX Programming Environment