fork

对于fork函数的说明:函数

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

  

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

 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\n");
12     else if (pid == 0)//子进程
13     {
14         printf("child1(%d)....\n", getpid());
15     }
16     else//父进程
17     {
18         printf("parent1(%d)...\n", getpid());
19     }
20     
21     printf("common:pid=%d\n", getpid());
22     
23     return 0;
24 }

 运行结果:blog

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

if (pid=fork() < 0)资源

{get

    printf("error\n");it

    exit(0);io

}class

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\n");
13     else if (pid == 0)//子进程
14     {
15         printf("child1(%d),pid=%d....\n", getpid(), pid);
16         printf("&count=%p, count=%d\n", &count, count);
17         ++count;
18         printf("&count=%p, count=%d\n", &count, count);
19     }
20     else//父进程
21     {
22         printf("parent1(%d),pid=%d...\n", getpid(), pid);
23         printf("&count=%p, count=%d\n", &count, count);
24     }
25     
26     printf("common:pid=%d\n", getpid());
27     
28     return 0;
29 }

运行结果:

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

相关文章
相关标签/搜索