先看一个简单的例子1:
#include <stdio.h>
#include <sys/types.h>
int main()
{
pid_t pid;
int i;
char *str = "hello!";
for (i = 0; i<2; i++) {
if ((pid = fork()) < 0) {
perror("fork");
return -1;
}
else if (pid == 0) { // child
printf("in child process pid,parent pid:%d\n", getpid(), getppid());
}
else { //parent
printf("in parent process pid:%d, child pid:%d\n", getpid(), pid);
return 0;
}
printf("%s,%d\n", str, getpid());
}
return 0;
}
结果:
in child process pid:4305,parent pid:4304
hello!,4305
in child process pid:4306,parent pid:4305
hello!,4306
in parent process pid:4305, child pid:4306
in parent process pid:4304, child pid:4305
再看一个例子2,仅去掉了父进程当中的return 0;语句:
#include <stdio.h>
#include <sys/types.h>
int main()
{
pid_t pid;
int i;
char *str = "hello!";
for (i = 0; i<2; i++) {
if ((pid = fork()) < 0) {
perror("fork");
return -1;
}
else if (pid == 0) { // child
printf("in child process pid,parent pid:%d\n", getpid(), getppid());
}
else { //parent
printf("in parent process pid:%d, child pid:%d\n", getpid(), pid);
//return 0;
}
printf("%s,%d\n", str, getpid());
}
return 0;
}
结果:
in child process pid:4331,parent pid:4330
hello!,4331
in child process pid:4332,parent pid:4331
hello!,4332
in parent process pid:4331, child pid:4332
hello!,4331
in parent process pid:4330, child pid:4331
hello!,4330
in child process pid:4333,parent pid:4330
hello!,4333
in parent process pid:4330, child pid:4333
hello!,4330
结合两个小例子的结果,自己分析一下,应该对父子进程资源共享有个大概的体验了吧.例1会产生2个子进程,例2会产生2^2-1个子进程.也就是说,如果父子进程中没有一个在for环循中退出去,那么如果有N次环循,会产生2^N-1个子进程(当然这些子进程中,只有N个是根父进程的子进程,其它的是子进程产生的子进程)