测试目的: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
源代码:
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <iostream>
- using namespace std;
- int main()
- {
- pid_t pid;
- int n = 0;
- int test = 100;
- printf("fork!/n");
- std::cout << "befooooore fork: " << test << " pid: " << getpid() << endl;
- n = fork();
- if(n < 0)
- {
- std::cout << "fork error: " << n << endl;
- }
- else if(n == 0)
- {
- //child process
- std::cout << "child fork: test: " << test << " pid: " << getpid() << endl;
- sleep(2);
- test += 10;
- std::cout << "child fork: test: " << test << endl;
- test += 20;
- sleep(2),
- std::cout << "child fork test: " << test << endl;
- test += 30;
- sleep(2),
- std::cout << "child fork test: " << test << endl;
- }
- else
- {
- //parent process
- std::cout << "parent fork: " << test << endl;
- test += 3;
- sleep(3);
- std::cout << "parent fork: " << test << endl;
- }
- sleep(10);
- std::cout << "eeeeend fork: " << test << " pid: " << getpid() << endl;
- std::cout << "hello, are you child or parent? pls" << endl;
- return 0;
- }
分析:fork后的所有源代码,将会被父子进程执行,而在fork过程中的数据,则是父子进程各保留一份,不再相互影响!
本文通过一个简单的C++程序演示了Linux环境下fork机制的工作原理。重点介绍了如何通过fork创建子进程,并展示了父进程与子进程间数据独立性的特性。实验结果显示,尽管初始数据被复制到子进程中,但后续两个进程各自修改数据时互不影响。
1293

被折叠的 条评论
为什么被折叠?



