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的调用不够方便........

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

  • 相关阅读:
    vue中的 computed 和 watch 的区别
    mysql8.0 初始化数据库及表名大小写问题
    sql server alwayson 调整数据文件路径
    zabbix 自定义监控 SQL Server
    mysql 创建用户及授权
    mysql 设置从库只读模式
    mysql8.0 主从复制安装及配置
    centos8.0安装mysql8.0
    centos8替换阿里数据源
    npm publish 报错 【you or one of your dependencies are requesting a package version that is forbidden by your security policy】
  • 原文地址:https://www.cnblogs.com/aLittleBitCool/p/2567114.html
Copyright © 2011-2022 走看看