您需要创建一个包含要运行的完整脚本的字符串,或者您需要创建一个可以简单运行的脚本,然后使用popen() 安排读取该脚本的输出。两者皆有可能;哪个更容易取决于您的脚本技能水平与您的 C 编程技能水平。
char command[4096];
strcpy(command, "TOTAL=$(free | grep Mem| awk '{print $2}')\n");
strcat(command, "grep -v procs $1 | grep -v free |\n");
strcat(command, "awk '{USED=TOTAL-$4-$5-$6;print USED}' TOTAL=$TOTAL\n");
FILE *in = popen(command, "r");
...read the results, etc...
字符串操作简化了第一个shell脚本,然后将计算得到的TOTAL的值传递给awk。
另一种方法是从free | grep Mem | awk '{print $2}' 读取输出 - TOTAL 值 - 从popen() 的一次使用中读取,然后将该值构建到第二个命令中:
char command[4096];
strcpy(command, "free | grep Mem| awk '{print $2}'");
char total[20];
FILE *in1 = popen(command, "r");
...read TOTAL into total...
strcpy(command, "grep -v procs $1 | grep -v free |\n");
strcat(command, "awk '{USED=TOTAL-$4-$5-$6;print USED}' TOTAL=");
strcat(command, total);
FILE *in2 = popen(command, "r");