zoukankan      html  css  js  c++  java
  • Linux下C语言执行shell命令

    有时候在代码中需要使用到shell命令的情况,下面就介绍一下怎么在C语言中调用shell命令:

    这里使用popen来实现,关于popen的介绍,查看 http://man7.org/linux/man-pages/man3/popen.3.html

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <errno.h>
     4 
     5 static long get_used_space(const char *dir) {
     6     long lUsedSpace = 0;
     7     char cmd[1024] = "";
     8     char buf[1024] = "";
     9     snprintf(cmd, 1024, "du -sk %s | awk '{print $1}'", dir);
    10     printf("%s
    ", cmd);
    11     FILE *pFile = popen(cmd, "r");
    12     if (pFile == NULL) {
    13         printf("popen() failed, error:%s
    ", strerror(errno));
    14         return lUsedSpace;
    15     }
    16     fgets(buf, sizeof(buf), pFile);
    17     pclose(pFile);
    18     lUsedSpace = atol(buf);
    19     return lUsedSpace;
    20 }
    21 
    22 int main()
    23 {
    24     long lUsedSpace = get_used_space("/var/log/");
    25     printf("UsedSpace:%ld
    ", lUsedSpace);
    26     return 0;
    27 }

     需要注意的是type参数,只能是读或写:

  • 相关阅读:
    2. 两数相加
    1. 两数之和
    x-pack elasticsearch
    简单的文档
    PHP imagepng函数 问题
    Nginx 配置
    nginx内置变量
    TCP通信
    mysql 的一些操作
    ubuntu 软件包降级
  • 原文地址:https://www.cnblogs.com/lit10050528/p/9720578.html
Copyright © 2011-2022 走看看