C Tutorial: Playing with processes

Creating a process

A new process is created with the fork system call. When fork is called, the operating system creates a new process: it assigns a new process entry in the process table and clones the information from the current one. All file descriptors that are open in the parent will be open in the the child. The executable memory image is copied as well. As soon as the fork call returns, both the parent and child are now running at the same point in the program. The only difference is that the child gets a different return value from fork. The parent gets the procsss ID of the child that was just created. The child gets a return of 0. If fork returns -1 then the operating system was unable to create the process.

The crucial thing to note with fork is that nothing is shared after the fork. Even though the child is running the same code and has the same files open, it maintains its own seek pointers (positions in the file) and it has its own copy of all memory. If a child changes a memory location, the parent won't see the change (and vice versa).

Example

This is a small program that clones itself. The parent prints a message stating its process ID and the child's process ID. It gets its process ID via the getpid system call and it gets its child's process ID from the return of fork. the child prints its process ID. The parent and child then each exit. Note that exit takes a parameter. This becomes the exit code of the program. The convention for Unix systems is to exit with a code of zero on success and a non-zero on failure. This helps in scripting programs.

/* fork: create a new process */ /* 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) { int pid; /* process ID */ switch (pid = fork()) { case 0: /* a fork returns 0 to the child */ printf("I am the child process: pid=%d\n", getpid()); break; default: /* a fork returns a pid to the parent */ printf("I am the parent process: pid=%d, child pid=%d\n", getpid(), pid); break; case -1: /* something went wrong */ perror("fork"); exit(1); } exit(0); }

Download this file

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

Compile this program via:

gcc -o fork fork.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:

./fork

Recommended

The Practice of Programming

 

The C Programming Language

 

The UNIX Programming Environment