linux命令C开发下使用常用函数system与popen开销比较

文章原文:http://blog.chinaunix.net/uid-23586172-id-3209020.html 网站Chinaunix首页

popen()  opens a process by creating a pipe, forking, and invoking the shell. 

system()  executes a command specified in command by calling /bin/sh -c command,and returns after the command has been completed.
system的过程是:fork(),exec(),waitpid().
popen的过程是:创建一个管道,fork一个子进程,关闭管道的不使用端,exec一个shell以运行命令,然后等待命令终止。

没看出popen会比system开销小啊?倒是还多创建一个管道用来传递数据,开销应该还会大些吧。。。如果同样是用来执行shell指令的话.
system() 调用 sh 解释器,popen() 则任意。popen() 打开管道,system() 往往设置一些信号处理方面的参数,二者皆有被调用进程外的开销。

注意的地方:
设置用户ID或者设置组ID的程序不应调用system函数,因为system经过fork、exec之后,权限会保留给运行的程序。应该直接用fork和exec,而且在exec之前要改回到普通权限。

我的实验:

点击(此处)折叠或打开

  1. #include "stdlib.h"
  2. #include "unistd.h"
  3. #include "stdio.h"

  4. int main()
  5. {
  6.     FILE * fp;
  7.     int i;
  8.     int j;
  9.     for(= 0; i < 10000; i++ )
  10.     {
  11.         system("ls -l >/dev/null");
  12.         //fp = popen("ls -l >/dev/null","r");
  13.         //pclose(fp);
  14.     }
  15.     return 0;
  16. }
/usr/bin/time测试
system: 
usr+sys = 0:53.05elapsed,  0:53.01elapsed
popen:
usr+sys = 0:53.61elapsed,  0:53.60elapsed
有理由相信,我的推断是正确的.在都执行shell程序的基础上,system运行效率更高。

TODO:运行其他程序的比较。
代码其实差不多,不过我们现在不直接执行ls-l,而是调用一个执行ls-l的程序atest,这样,popen就会比system少fork一个shell,看看结果。

点击(此处)折叠或打开

  1. #include "stdlib.h"
  2. #include "unistd.h"
  3. #include "stdio.h"

  4. int main()
  5. {
  6.     FILE * fp;
  7.     int i;
  8.     int j;

  9.     for(= 0; i < 10000; i++ )
  10.     {
  11.         //system("./atest");
  12.         fp = popen("./atest","r");
  13.         pclose(fp);
  14.     }

  15.     return 0;

  16.     
  17. }
system:
usr+sys 1:20.34elapsed
usr+sys 1:20.32elapsed
popen:
1:20.94elapsed
1:20.86elapsed
popen的开销还是会大一些。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值