曲径通幽论坛

标题: fork() 和 vfork() 的区别 [打印本页]

作者: beyes    时间: 2009-6-16 00:34
标题: fork() 和 vfork() 的区别
vfork() 也可以用来创建一个新进程,与 fork相比,他有自己独特的用处,以下是两者的差异的一个详细对比:
因为使用 fork() 创建一个子进程时,子进程需要将父进程几乎每种资源都复制,所以 fork() 是一个开销很大的系统调用,这些开销并不是所有的情况都需要。比如,fork() 一个进程后,立即调用 exec() 执行另外一个应用程序,那么 fork() 过程中子进程对父进程地址空间的复制将是ige多余的过程。vfork() 不会拷贝父进程的地址空间,这大大减小了系统开销。

示例程序:
[C++] 纯文本查看 复制代码

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int globVar = 5;

int main(void)
{
    pid_t pid;
    int i, var = 1;

    printf("fork is different with vfork \n");

    pid = fork();
   
    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("Perent process is running\n");
                globVar++;
                var++;
                sleep(1);
            }
        printf("Perent's GlobVar = %d, var = %d\n", globVar, var);
        exit(0);
    }
exit(0);
}

编译并运行这个程序
beyes@linux-beyes:~/C/base> ./diffork.exe
fork is different with vfork
Perent process is running
Child process is running
Perent process is running
Child process is running
Child process is running
Perent process is running
Child's globVar = 8, var = 4
Perent process is running
Perent process is running
Perent's GlobVar = 10, var = 6

把上面程序中 pid = fork(); 改成 pid = vfork(); 然后再次编译运行:
[beyes@localhost syscall]$ ./vfork
fork is different with vfork
Child process is running
Child process is running
Child process is running
Child's globVar = 8, var = 4
Perent process is running
Perent process is running
Perent process is running
Perent process is running
Perent process is running
Perent's GlobVar = 13, var = 9

对比上面两个程序,可以看到,vfork() 出来的子进程和父进程共享了全局变量 GlobVar 以及局部变量 var ,而且 vfork() 保证了子进程先运行结束然后再到父进程。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2