fork

对于fork函数的说明:

只共享代码段,但是数据段、堆、栈子进程也会从父进程中拷贝副本,但是并不是和父进程共享相关资源,而是在自己的进程空间中维护。

  

下面这个例子主要是针对“共享代码段”进行说明

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <sys/types.h>
 4 #include <unistd.h>
 5 
 6 int main(int argc, char** argv)
 7 {
 8     pid_t pid;
 9 
10     if ((pid = fork()) < 0)
11         printf("fork error
");
12     else if (pid == 0)//子进程
13     {
14         printf("child1(%d)....
", getpid());
15     }
16     else//父进程
17     {
18         printf("parent1(%d)...
", getpid());
19     }
20     
21     printf("common:pid=%d
", getpid());
22     
23     return 0;
24 }

 运行结果:

common部分的代码是很容易被忽视的地方。所以呢,为了防止代码复杂后导致common部分区分不清,最好使用如下形式:

if (pid=fork() < 0)

{

    printf("error ");

    exit(0);

}

else if (pid == 0)

{

    do someting in child process

}

else

{

    do sometion in father process

}

do nothing

return;

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <sys/types.h>
 4 #include <unistd.h>
 5 
 6 int main(int argc, char** argv)
 7 {
 8     pid_t pid;
 9     int count = 0;
10 
11     if ((pid = fork()) < 0)
12         printf("fork error
");
13     else if (pid == 0)//子进程
14     {
15         printf("child1(%d),pid=%d....
", getpid(), pid);
16         printf("&count=%p, count=%d
", &count, count);
17         ++count;
18         printf("&count=%p, count=%d
", &count, count);
19     }
20     else//父进程
21     {
22         printf("parent1(%d),pid=%d...
", getpid(), pid);
23         printf("&count=%p, count=%d
", &count, count);
24     }
25     
26     printf("common:pid=%d
", getpid());
27     
28     return 0;
29 }

运行结果:

上面的例子中表明,虽然count变量被子进程从父进程复制过来,而且变量的地址都是一样的,但是count变量在父子进程中,尽管逻辑地址相同但物理地址肯定不同,所以不同的进程,进程的地址空间是不一样的。

原文地址:https://www.cnblogs.com/black-mamba/p/6821000.html