0

我的问题很简单:

我正在用 C 编写一个具有以下结构的程序:

int qty_used;

qty_used = system("df -h | grep 'sda1' | awk 'BEGIN{print "Use%"} {percent+=$5;} END{print percent}'");

if (qty_used<fixed_limit)
   /* action 1 */
else
   /* action 2*/;

因此,如果是这种情况:

Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1       2.0T   30G  1.8T   2% /

我希望 qty_used 加载整数值 2。我以前从未使用过 awk,我从这个有希望的答案开始:https ://unix.stackexchange.com/questions/64815/how-to-print-the-percentage-of -disk-use-from-df-hl。输出:

df -h | grep 'sda1' | awk 'BEGIN{print "Use%"} {percent+=$5;} END{print percent}'

听起来不错。但如果我要求 [我只想要整数]:

df -h | grep 'sda1' | awk 'BEGIN{percent+=$5;} END{print percent}'

然后输出为零,不再是 2

此外,我知道系统不会返回我正在搜索的百分比,而是返回对我的需求无用的命令状态

所以问题是:有没有从这些方面开始解决这个问题的快速方法?

感谢那些愿意提供帮助的人

4

3 回答 3

1

您需要了解该system()函数返回与命令的退出代码相关的值,而不是与命令的输出相关的任何值。您还需要了解可能的退出代码范围非常小。

话虽如此,如果您只需要支持 0 到 100 之间的整数值,那么您应该能够使用适当的代码使命令退出。这应该这样做:

#include <sys/types.h>
#include <sys/wait.h>

/* ... */

    qty_used = WEXITSTATUS(
            system("exit `df -h | awk '/sda1/{percent+=$5;} END{print percent}'`"));

更新grep根据@EdMorton 的评论,从命令管道中删除了。

于 2015-03-02T23:23:52.717 回答
0

这会增加 BEGIN 块中的百分比...

$ df -h | grep 'sda1' | awk 'BEGIN{percent+=$5;} END{print percent}'
0

请比较(也许这是本意?)

$ df -h | grep 'sda1' | awk 'BEGIN{percent=0;} {percent+=$5;} END{print percent}'
2

此外,系统返回命令的状态,而不是其输出。请考虑使用 popen 并从流中读取。

作为使用 popen 的示例...

#include <stdio.h>
#include <string.h>

#define SIZE 2048

int get_percent_used (const char* devicename);

int main(int argc, char** argv) {
    int qty_used = get_percent_used("/dev/sda1");
    printf ("qty_used = %d percent\n", qty_used);
    return 0;
}

int get_percent_used (const char* devicename)
{
    char buffer[SIZE];
    char command[SIZE];
    FILE* pipe = 0;
    int percent = 0;

    sprintf (command, "df -h | grep '%s' | awk 'BEGIN{percent=0;} {percent+=$5;} END{print percent}'", devicename);

    if (!(pipe = popen(command, "r"))) {
        perror("open failed");
        return 1;
    }

    while (fgets(buffer, SIZE, pipe) != NULL) {
        percent += (int) strtol(buffer, NULL, 10);
    }
    pclose(pipe);

    return percent;
}
于 2015-03-02T23:42:43.523 回答
0

一种简单的方法...

让最后一个函数(awk)将输出重定向到文件(使用'>文件名')

然后打开文件进行阅读并提取所需的信息。

于 2015-03-02T22:58:21.350 回答