fork()与vfork()函数都能创建一个新的进程,区别在于fork()创建的新进程完全复制了父进程的资源(包含变量),可以成为一个独立的进程;vfork()创建的进程不复制父进程的资源,它与父进程共享资源。下面是代码示例:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int globVar=5;
int main()
{
pid_t pid;
int var=1;
int i;
pid=fork(); //显示的结果
//pid=vfork();
switch (pid)
{
case 0:
i=3;
while (i-->0)
{
printf("child process is running\n");
globVar++;
var++;
sleep(1);
}
printf("child's globVar=%d,var=%d\n",globVar,var);
break;
case -1:
perror("process creation failed\n");
exit(0);
default:
i=5;
while (i-->0)
{
printf("parent process is running!\n");
globVar++;
var++;
sleep(1);
}
printf("parent's glovVar=%d,var=%d\n",globVar,var);
exit(0);
}
}
运行的结果:
当 pid=fork()时,child process is running
parent process is running
child process is running
parent process is running
child process is running
parent process is running
child's globVar=8,var=4
parent process is running
parent process is running
parent's glovVar=10,var=6
当注释掉pid=fork(),取消程序中的注释行时,即使用vfork创建子进程,运行结果如下:
child process is running
child process is running
child process is running
child's globVar=8,var=4
parent process is running
parent process is running
parent process is running
parent process is running
parent process is running
parent's glovVar=13,var=3