zoukankan      html  css  js  c++  java
  • 有关 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的调用不够方便........

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

  • 相关阅读:
    Git SVN 版本控制 简介 总结 MD
    shape selector 背景 圆形 矩形 圆环 [MD]
    eclipse library jar包 使用总结 MD
    Visitor 访问者模式 [MD]
    BlazeMeter+Jmeter 搭建接口测试框架
    nGrinder 简易使用教程
    65个面试常见问题技巧回答(绝对实用)
    [面试技巧]16个经典面试问题回答思路
    质量模型测试电梯
    linux apache服务器优化建议整理(很实用)
  • 原文地址:https://www.cnblogs.com/aLittleBitCool/p/2567114.html
Copyright © 2011-2022 走看看