linux 在应用程序中 使用shell命令获取数据
Posted 为了维护世界和平_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux 在应用程序中 使用shell命令获取数据相关的知识,希望对你有一定的参考价值。
在程序中使用命令行执行的结果
比如使用top命令查看系统状态
root@ubuntu:~# top
top - 05:26:18 up 6 days, 22:52, 1 user, load average: 0.14, 0.14, 0.37
Tasks: 429 total, 1 running, 327 sleeping, 2 stopped, 0 zombie
%Cpu(s): 0.6 us, 1.0 sy, 0.0 ni, 98.4 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 8117312 total, 772760 free, 2561432 used, 4783120 buff/cache
KiB Swap: 2097148 total, 2096624 free, 524 used. 5193880 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1732 wy 20 0 4381796 336160 84612 S 7.3 4.1 21:07.54 gnome-shell
1604 wy 20 0 579688 119156 74032 S 3.7 1.5 11:06.95 Xorg
2067 wy 20 0 851416 60504 36636 S 2.3 0.7 4:46.19 gnome-terminal-
1754 wy 20 0 2382772 17284 13476 S 0.7 0.2 94:00.18 pulseaudio
1771 wy 20 0 428516 8548 6368 S 0.7 0.1 1:49.78 ibus-daemon
1 root 20 0 225804 9436 6564 S 0.3 0.1 0:30.64 systemd
477 root -51 0 0 0 0 S 0.3 0.0 0:28.41 irq/16-vmwgfx
1886 wy 20 0 652236 25248 16596 S 0.3 0.3 3:58.37 gsd-color
2407 wy 20 0 4633804 597844 254212 S 0.3 7.4 26:07.75 firefox
想截取系统的CPU使用率,如何在C程序中使用这个值呢?
root@ubuntu:~# top -b -n1 | grep -n %Cpu | cut -d ':' -f 3| cut -d ',' -f 2
0.2 sy
1、借助函数popen
popen()函数通过创建一个管道,调用fork()产生一个子进程,执行一个shell以运行命令来开启一个进程。注意函数关闭是pclose()
可以直接提取结果,不需要中转
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
char* cmd = "top -b -n1 | grep -n %Cpu | cut -d ':' -f 3| cut -d ',' -f 2";
FILE* fp = NULL;
char buf[1024] = 0;
fp = popen(cmd, "r");
if (NULL == fp)
printf("popen faild. (%d, %s)\\n",errno, strerror(errno));
return -1;
fread(buf, 1, sizeof(buf), fp);
printf("res: %s\\n", buf);
pclose(fp);
return 0;
root@ubuntu:~# ./a.out
res: 0.2 sy
2,使用system()
结果可以写在文件中,再从文件中获取想要的数据。
程序先将结果保存在a.txt中,可以再从a.txt中获取数据。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
system("top -b -n1 | grep -n %Cpu | cut -d ':' -f 3| cut -d ',' -f 2 > a.txt");
return 0;
~
root@ubuntu:~# cat a.txt
0.2 sy
以上是关于linux 在应用程序中 使用shell命令获取数据的主要内容,如果未能解决你的问题,请参考以下文章