We have also seen how the operating system uses

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: the parent or the child. Figure 8.13 shows a simple example of a parent process that uses fork to create a child process. When the fork call returns in line 8, x has a value of 1 in both the parent and child. The child increments and prints its copy of x in line 10. Similarly, the parent decrements and prints its copy of x in line 15. code/ecf/fork.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include "csapp.h" int main() { pid_t pid; int x = 1; pid = Fork(); if (pid == 0) { /* child */ printf("child : x=%d\n", ++x); exit(0); } /* parent */ printf("parent: x=%d\n", --x); exit(0); } code/ecf/fork.c Figure 8.13: Using fork to create a new process. When we run the program on our Unix system, we get the following result: 406 unix> ./fork parent: x=0 child : x=2 CHAPTER 8. EXCEPTIONAL CONTROL FLOW There are some subtle aspects to this simple example. ¯ ¯ Call once, return twice. The fork function is called once by the parent, but it returns twice: once to the parent and once to the newly created child. This is fairly straightforward...
View Full Document

This note was uploaded on 09/02/2010 for the course ELECTRICAL 360 taught by Professor Schultz during the Spring '10 term at BYU.

Ask a homework question - tutors are online