Tuesday, July 24, 2012

fork():,


fork():

The fork() system call will spawn a new child process which is an identical process to the parent except that has a new system process ID. The process is copied in memory from the parent and a new process structure is assigned by the kernel. The return value of the function is which discriminates the two threads of execution. A zero is returned by the fork function in the child's process.
The environment, resource limits, umask, controlling terminal, current working directory, root directory, signal masks and other process resources are also duplicated from the parent in the forked child process. 



#include <iostream>
02#include <string>
03 
04// Required by for routine
05#include <sys/types.h>
06#include <unistd.h>
07 
08#include <stdlib.h>   // Declaration for exit()
09 
10using namespace std;
11 
12int globalVariable = 2;
13 
14main()
15{
16   string sIdentifier;
17   int    iStackVariable = 20;
18 
19   pid_t pID = fork();
20   if (pID == 0)                // child
21   {
22      // Code only executed by child process
23 
24      sIdentifier = "Child Process: ";
25      globalVariable++;
26      iStackVariable++;
27    }
28    else if (pID < 0)            // failed to fork
29    {
30        cerr << "Failed to fork" << endl;
31        exit(1);
32        // Throw exception
33    }
34    else                                   // parent
35    {
36      // Code only executed by parent process
37 
38      sIdentifier = "Parent Process:";
39    }
40 
41    // Code executed by both parent and child.
42   
43    cout << sIdentifier;
44    cout << " Global variable: " << globalVariable;
45    cout << " Stack variable: "  << iStackVariable << endl;
46} 





                                                                      

No comments:

Post a Comment