/* File: ~liux/public_html/courses/cop4610/examples/simple-fork.cc Purpose: Demonstrate how to use fork system call COP4610 Author: Xiuwen Liu On the web: http://www.cs.fsu.edu/~liux/courses/cop4610/examples/simple-fork.cc Compile: g++ -o simple-fork simple-fork.cc */ /* One running example ./simple-fork running.out */ /* more running.out A message line with i = 0 from 1624 whose parent is 14850 A message line with i = 1 from 1624 whose parent is 14850 A message line with i = 1 from 1625 whose parent is 1624 A message line with i = 2 from 1625 whose parent is 1624 A message line with i = 2 from 1624 whose parent is 14850 A message line with i = 2 from 1627 whose parent is 1625 A message line with i = 2 from 1626 whose parent is 1624 */ /* Questions: 1. How many new processes are created by running this program? 2. Can you explain why the file "running.out" contains the information as shown above? */ #include #include #include #include #include int main(int argc, char *argv[]) { char fname[256]; if (argc <2) { cout << "Please give a file name to save output messages: "; cin >> fname; } else { strcpy(fname,argv[1]); } ofstream outFile(fname); int i = 0; while( i < 3) { cout << "A message line with i = " << i << endl; outFile << "A message line with i = " << i << " from " << getpid() << " whose parent is " << getppid() << endl; fork(); i++; } outFile.close(); return 0; }