有关 vfork + exec 与 system 的效率对比

最近主要研究了下system函数的效率以及学习了下vfork函数。简单的做了一个小测试,对比了下使用system与vfork + exec的效率问题。

 

system函数相信大家都不陌生,主要用于调用其他程序。不同系统的system函数的实现也是不同的。

 

vfork函数和fork函数在功能上基本是一致的,都是创建一个子进程。不同的是vfork不会拷贝父进程的地址空间,并且能保证子进程先于父进程执行。使用vfork主要是为了之后子进程调用exec函数族,因为省去了拷贝父进程地址空间的步骤,因此效率可能稍微高一点。

 

以下是测试代码:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<string.h>

int call_system()
{
    int i;

    for(i = 0; i < 100; i++){
        system("ls -l");
    }

    return 0;
}

int call_vfork()
{
    int i;
    pid_t child_pid;

    for(i = 0; i < 100; i++){
        if((child_pid = vfork()) < 0){ 
            fprintf(stderr, "vfork error\n");   
            return -1; 
        }   
        else if(child_pid == 0){    /*child*/
            execl("/bin/ls", "ls", "-l", (char *)0);
        }   
        else{                       /*father*/
            waitpid(child_pid, NULL, 0); 
        }   
    }   

    return 0;
}

int main(int argc, char *argv[])
{
    if(argc < 2){ 
        fprintf(stdout, "less parameters\n");
        return 0;
    }

    if(strcmp(argv[1], "system") == 0){
        call_system();
    }
    else if(strcmp(argv[1], "vfork") == 0){
        call_vfork();
    }
    else{
        fprintf(stdout, "parameter should be system or vfork !\n");
    }

    return 0;
}

利用time -p分别对两个函数进行测试发现vfork + exec执行的效率稍微比system高一点,。但是感觉在实际使用的过程中还是使用system函数方便点,原因就是因为exec的调用不够方便........

 

任务有点重呀.......

posted @ 2012-06-28 09:35  akawhy  阅读(2435)  评论(1编辑  收藏  举报