Using the fork system call

The fork(2) system call creates a new process. Listing 2 shows fork being used in a simple piece of C code.

The code in fork1.c simply makes the call to fork and prints the integer result through a call to printf. Only one call is made, but the output is printed twice. This is because a new process is created within the call to fork. Two separate processes are now returning from the call. This is often described as “called once, returns twice.”

The values returned by fork are interesting. One of them returns 0; the other, a non-zero value. The process that gets the 0 is called the child process, and the non-zero result goes to the original process, which is the parent process. You use the return value to determine which process is which. Because both processes resume execution at the same space, the only practical differentiator is the return value from fork.

The rationale for the 0 and non-zero return values is that a child can always find out who its parent is through a call to getppid(2), but it is more difficult for a parent to find all its children. Thus, the parent is told about its new child, and the child can look up its parent, if needed.

With the return value of fork in mind, the code can now check to see if it is the parent or child process and act accordingly. Listing 3 shows a program that prints different output based on the result of the fork.

Related Post

GlossaryGlossary

If required, IBM provides repair or exchange service depending on the type of warranty service specified for your Machine. Warranty service may be by your reseller if approved by IBM