【问题标题】:how to add a command to check battery level in linux shell?如何在 linux shell 中添加命令来检查电池电量?
【发布时间】:2014-03-02 13:42:09
【问题描述】:

我正在编写一个迷你 UNIX shell,它支持内置的 UNIX 命令以及一些自定义命令。我需要以

的样式检查我的 C-shell 代码中的电池电量
if (strcmp("BatteryLevel", commandArgv[0]) == 0) {

                printf("The battery level is ",);
                return 1;
        }  

我已经编写了 shell 块,所有的解析和内置命令都在工作。我也知道如何从终端检查电池电量(https://askubuntu.com/questions/69556/how-to-check-battery-status-using-terminal),但我无法理解如何在代码中执行此操作。 谢谢你的帮助。

【问题讨论】:

标签: c linux shell


【解决方案1】:

对于 3.4.NN 内核,当前电池电量和可以达到的最大值可在文件 charge_nowcharge_full 中的 /sys/class/power_supply/BAT*(通常是 BAT0,因为您通常只有一节电池)中提供。因此,以下内容应该可以满足您的需求。

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <linux/limits.h>
#include <regex.h>

#define _DATADIR "/sys/class/power_supply"

int main(int argc, char **argv) {
  FILE *f_c, *f_f;
  long current, full;
  DIR *d;
  struct dirent *dp;
  char b[PATH_MAX]; 

  if((d = opendir(_DATADIR)) == NULL) {
    fprintf(stderr, "opendir: %s\n", strerror(errno));
    return 3;
  }

  while((dp = readdir(d)) != NULL) {
    snprintf(b, PATH_MAX, "%s/%s", _DATADIR, dp->d_name);

    regex_t regex;
    if(regcomp(&regex, "BAT[[:alnum:]]+", REG_EXTENDED) != 0) {
      fprintf(stderr, "regcomp: %s\n", strerror(errno));
      return 4;
    }
    if(regexec(&regex, b, 0, NULL, 0) == 0) {
      snprintf(b, PATH_MAX, "%s/%s/%s", _DATADIR, dp->d_name, "charge_now");
      f_c = fopen(b, "r");
      snprintf(b, PATH_MAX, "%s/%s/%s", _DATADIR, dp->d_name, "charge_full");
      f_f = fopen(b, "r");
      if(f_c != NULL && f_f != NULL) {
        if(fscanf(f_c, "%ld", &current) != 1 || fscanf(f_f, "%ld", &full) != 1)
          fprintf(stderr, "fscanf: %s\n", strerror(errno));
        else
          fprintf(stdout, "charge for %s %.2f\n", dp->d_name,
                  (current / full) * 100.0);
        fclose(f_c);
        fclose(f_f);
      }
    }
    regfree(&regex);
  }

  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多