c ++ concurrent programming of process creation

 

1. Process Creation

First on the code:

. 1   #include " the iostream "                                                                                                                                         
2   #include <unistd.h>
 . 3     int main ()
 . 4     { 
 . 5         the using  namespace STD;
 . 6         pid_t PID;
 . 7        COUT << " ! Parent have have " << endl;
 . 8             PID = the fork (); // when the fork is in the end what happened? 
9         IF (pid == - 1 ) // error creating 
10         {
 11             perror ( " fork error " );
 12              _exit(1);
13        }
14        else if(pid == 0)//子进程
15        {
16 
17            cout<<"i am child,pid = "<<getpid()<<" my parent is:"<<getppid()<<endl;
18        }
19        else//父进程
20        {
21           // sleep(1);
22            cout<<"i am parent,pid = "<<getpid()<<" my parent is:"<<getppid()<<endl;
23        }
24        cout<<"both have!"<<endl;
25        return 0;
26    }

operation result:

 

 

 Procedures and results analysis:

 

 

 

2. Create multiple sub-processes

. 1   #include " the iostream "                                                                                                                                         
2   #include <unistd.h>
 . 3     int main ()
 . 4     { 
 . 5         the using  namespace STD;
 . 6         pid_t PID;
 . 7        COUT << " parent have have! " << endl;
 . 8        for ( int I = 0 ; I < . 5 ; I ++ )
 . 9        {
 10              PID = fork (); // ? when the fork in the end of what happened 
. 11              IF (PID == 0 )
 12 is             {
 13 is                 // COUT << "The Son ID of" I + << <<. 1 ":" << getpid () << endl; 
14                   BREAK ; // this is very important, consider why 
15              }
 16        }
 . 17           
18 is         IF (PID == - . 1 ) // error created 
. 19         {
 20 is             perror ( " the fork error " );
 21 is               _exit ( . 1 );
 22 is         }
 23 is         the else  IF (PID == 0 ) // sub-process 
24         {
 25            //sleep(1);
26            cout<<"i am child,pid = "<<getpid()<<" my parent is:"<<getppid()<<endl;
27        }
28        else//父进程
29        {
30            sleep(1);
31            cout<<"i am parent,pid = "<<getpid()<<" my parent is:"<<getppid()<<endl;
32        }
33        cout<<"both have!"<<endl;
34        return 0;
35    }

Result of the program:

 

 

 Procedures and results analysis:

 

 

Father and son sharing process

Follow the principle of sharing: Copy the principle of shared read-write

Guess you like

Origin www.cnblogs.com/shaonianpi/p/11442915.html