子进程会拷贝父进程的所有资源,变量。
注意:子进程拷贝了父进程数据空间、堆、栈等资源的副本,
父子进程间不共享这些存储空间,共享的空间只有代码段,
子进程修改一个全局变量,父进程的这个全局变量不会改变,因为是一个副本。
所以下面的程序子进程不会输出:
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
pid = fork();
int countf = 0;
int counts = 0;
int n = 0;
if(pid == -1){
perror("fork failed");exit(1);
}
else if (pid > 0) {
sleep(1); // wait for sub-process exit, except to be a orphan
while(1) {
printf("parent_pid = %d, parentID = %d\n", getpid(), getppid());
scanf("%d", &n);
countf++;
}
}
else if (pid == 0) {
while(1){
if(counts != countf)
printf("child_pid = %d, parentID = %d, count=%d\n", getpid(), getppid(), countf);
counts = countf;
}
}
printf("This is an end