Welcome to pickSourcecode.com Login | Register    
pickZy.com
 Home  | search  | games  | General  | C  | C++  | Java  | Php  | Networking  | Visual Basic  | VC++  | Win32  | MFC  | JavaScript  | Jobs  | JavaScript  | Post jobs
Create Child Process - fork(): Sample program       Share
2009-09-18 |  RatheeshTR  | Viewed: 925  |    0


//  Create  Child  Process  -  fork():

#include <iostream>
#include <string>

//  Required  by  for  routine
#include <sys/types.h>
#include <unistd.h>

using namespace std;


int globalVariable = 2;

main()

{

   string sIdentifier;

   
int    iStackVariable = 20;

   pid_t pID = 
fork();
   
if (pID == 0)                //  child
   {

      
//  Code  only  executed  by  child  process

      sIdentifier = "Child Process: ";

      globalVariable++;

      iStackVariable++;

    }

    else 
if (pID < 0)            //  failed  to  fork
    {

        cerr << "Failed to 
fork" << endl;
        exit(1);

        
//  Throw  exception
    }

    else                                   
//  parent
    {

      
//  Code  only  executed  by  parent  process

      sIdentifier = "Parent Process:";

    }


    
//  Code  executed  by  both  parent  and  child.
  

    cout << sIdentifier;

    cout << " Global variable: " << globalVariable;

    cout << " Stack variable: "  << iStackVariable << endl;

}


Compile: g++ -o ForkTest ForkTest.cpp

Run: ForkTest


Parent Process: Global variable: 2 Stack variable: 20

Child Process:  Global variable: 3 Stack variable: 21


Latest topics
C - pointers to pointers  Viewed: 263
C - switch statement  Viewed: 264
C - binary tree  Viewed: 264
Malloc Debugger  Viewed: 264
Is a prime number or not  Viewed: 264
C - Do while  Viewed: 265
C - Global variables , static variables  Viewed: 265
C - binsearch  Viewed: 265
C Assign content to a function pointer  Viewed: 265
C - Structure example  Viewed: 266

Comments:





Submit comment's

Type:

User Comment's:

Submitted By:
Prof: Software Engineer
Tech: C ,Cpp
Send Mail: ratheesh



Related topics
C - Data Structure,Rev Linked list
C - Data Structure,linked list
C - time_t strftime example
C - time_t gmtime example
C - enum example
C - strtok example, Splitting string into tokens
C - libxml2 parsing example libxml
C - if else example
C - Structure example
C - pointers and arrays example strlen
C - Pointers to structures
C - gtk scrolled window example
C - Binary Search Tree example
C TCP socket example Server and Client program
C UDP socket example Server and Client program

Related References
c - basics of structure
c - functions and program structure, programmed pass-by-reference via pointers, pass-by-reference parameters
c - structures and functions
c - arrays of structures
c - pointers to structures
explain function pointers with examples?

Web site contents © Copyright 2007, All rights reserved.
Help | Terms and Conditions | Privacy Policy | About Us