程序源码:
[cce_cpp] #include <stdio.h> #include <stdlib.h> #include <unistd.h> int global; int main(){//3242进程 pid_t pid; int *heap; int stack; heap = (int*)malloc(sizeof(int)); pid = fork();//3242->3243 global = 1; *heap = 2; stack = 3; pid = fork();//3242->3244 3243->3245 if(pid<0){ printf("fail to fork\n"); exit(1); } else if(pid ==0){ printf("this is the child,pid is :%u\n",getpid()); global*=10; *heap*=10; stack*=10; printf("child:%u global:%d heap:%d stack:%d \n",getpid(),global,*heap,stack); } else{ printf("this is the parent,pid is %u,child pid is %u\n",getpid(),pid); printf("parent:%u global:%d heap:%d stack:%d \n",getpid(),global,*heap,stack); sleep(2); printf("parent:%u global:%d heap:%d stack:%d \n",getpid(),global,*heap,stack); } while(1);//使当前程序暂停运行,可以通过ps -elf来输出下列进程信息 return 0; } [/cce_cpp]
进程列表:
[cce] F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD 4 S root 1 0 0 80 0 - 1352 SyS_ep Feb19 ? 00:00:09 /sbin/init 4 S root 402 1 0 80 0 - 1952 poll_s Feb19 ? 00:00:00 /usr/sbin/sshd -D 4 S root 3096 402 0 80 0 - 2909 poll_s 01:15 ? 00:00:00 sshd: pi [priv] 5 S pi 3106 3096 0 80 0 - 2909 poll_s 01:15 ? 00:00:00 sshd: pi@pts/0 0 S pi 3109 3106 0 80 0 - 1578 wait 01:15 pts/0 00:00:01 -bash 每开一个终端,都会产生一个bash 0 R pi 3242 3109 94 80 0 - 449 - 01:52 pts/0 00:00:44 ./fork 1 R pi 3243 3242 94 80 0 - 449 - 01:52 pts/0 00:00:44 ./fork 1 R pi 3244 3242 98 80 0 - 449 - 01:52 pts/0 00:00:46 ./fork 1 R pi 3245 3243 99 80 0 - 449 - 01:52 pts/0 00:00:46 ./fork [/cce]
执行结果
[cce] this is the parent,pid is 3242,child pid is 3244 //3242进程虽然产生了两个子进程,但是只会执行一遍printf parent:3242 global:1 heap:2 stack:3 this is the parent,pid is 3243,child pid is 3245 parent:3243 global:1 heap:2 stack:3 this is the child,pid is :3245 child:3245 global:10 heap:20 stack:30 this is the child,pid is :3244 child:3244 global:10 heap:20 stack:30 parent:3242 global:1 heap:2 stack:3 parent:3243 global:1 heap:2 stack:3 [/cce]
通过返回数据的分析,说明子进程是将父进程的现状进行了复制,并非共享,子进程对于变量的相关操作不会影响父进程。