如何shell命令的输出分配给C语言的变量 [英] How to assign shell command output to a variable in C language
问题描述
我要的shell命令的输出(无回音| grep的纪念品| awk的'{打印$ 2}
)收集在一个变量,这样我可以用它C程序。所以,我有code在这里。
I want the output of the shell command (echo free | grep Mem| awk '{print $2}'
) collected in a variable so that I can use it in a C program. So I have the code here.
system("TOTAL=$(echo `free | grep Mem| awk '{print $2}'`)");
popen("grep -v procs $1 | grep -v free | awk '{USED=TOTAL-$4-$5-$6;print USED}'", "r");
我可以使用同样的程序中的变量TOTAL一个的popen()调用中,如上图所示?
Can I use the variable TOTAL in the same program inside a popen() call as shown above ?
推荐答案
您需要创建一个包含您要运行完整的脚本中的字符串,或者您需要创建一个可以简单地运行一个脚本,然后安排与的popen读取脚本输出()
。无论是可能的;哪一个更容易取决于你的脚本技能水平与你的C ++编程技巧。
You will need to create a string which contains the complete script that you want run, or you will need to create a script which can be run simply, and then arrange to read the output of that script with popen()
. Either is possible; which is easier depends on the level of your scripting skills vs your C programming skills.
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脚本,然后通过计算 AWK
总量的值。
其他的方式做这将是读免费的输出| grep的纪念品| AWK'{打印$ 2}
- 这是总价值 - 从一个使用的popen()
,那么构建值到第二个命令
The other way to do it would be to read the output from free | grep Mem | awk '{print $2}'
- the value that is TOTAL - from one use of popen()
, then build that value into the second command:
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");
这篇关于如何shell命令的输出分配给C语言的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!