fork过程中数据复制测试

来源:互联网 发布:合作社软件 编辑:程序博客网 时间:2024/04/29 02:53

 

测试目的:fork过程中,父进程的数据会被copy到子进程中,但是,从此之后,两个进程相互执行,互不干扰。这,也许就是进程空间内的数据概念啦。

 

测试环境:suse Linux

 

测试步骤:执行程序,查看结果

 

执行结果:

fork!
befooooore fork: 100 pid: 28895
parent fork: 100
child fork: test: 100 pid: 28896
child fork: test: 110
parent fork: 103
child fork test: 130
child fork test: 160
eeeeend fork: 103 pid: 28895
hello, are you child or parent? pls
eeeeend fork: 160 pid: 28896
hello, are you child or parent? pls

 

源代码:

 

 

 

  1. #include <sys/types.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <iostream>
  5. using namespace std;
  6. int main()
  7. {
  8.     pid_t pid;
  9.     int n = 0;
  10.     int test = 100;
  11.     printf("fork!/n");
  12.     
  13.     std::cout << "befooooore fork: " << test << " pid: " << getpid() << endl;
  14.     n = fork();    
  15.     if(n < 0)
  16.     {
  17.         std::cout << "fork error: " << n << endl;
  18.     }
  19.     else if(n == 0)
  20.     {
  21.         //child process
  22.         std::cout << "child fork: test: " << test << " pid: " << getpid() << endl;
  23.         
  24.         sleep(2);
  25.         test += 10;
  26.         std::cout << "child fork: test: " << test << endl;
  27.         
  28.         test += 20;
  29.         sleep(2),
  30.         std::cout << "child fork test: " << test << endl;
  31.         
  32.         test += 30;
  33.         sleep(2),
  34.         std::cout << "child fork test: " << test << endl;
  35.     }
  36.     else
  37.     {
  38.         //parent process
  39.         std::cout << "parent fork: " << test << endl;
  40.         
  41.         test += 3;
  42.         sleep(3);
  43.         std::cout << "parent fork: " << test << endl;
  44.     }
  45.     
  46.     sleep(10);
  47.     std::cout << "eeeeend fork: " << test << " pid: " << getpid() << endl;
  48.     
  49.     std::cout << "hello, are you child or parent? pls" << endl;
  50.     
  51.     return 0;

分析:fork后的所有源代码,将会被父子进程执行,而在fork过程中的数据,则是父子进程各保留一份,不再相互影响!