使用popen()执行shell命令并获取内容



1.popen通过管道获取shell的输出结果,跟重定向(ls > /test.txt)类似。

root@Easy-link:~# cat /proc/uptime
67.23 19.08

char*get_uptime()
{
  float hours;
  FILE *fp;
  static char buf[16];
  fp = popen("cat /proc/uptime |cut -d \" \" -f1","r");
  fgets(buf,sizeof(buf),fp);
  pclose(fp);
  hours = (atof(buf))/3600.00;
  sprintf(buf,"Uptime:%7.2f H",hours);
  return buf;
}
char*get_date()
{
   FILE *fp;
   static char buf[16];
   //fp = popen("date '+%y/%m/%d %I:%M%p'","r");
   fp = popen("date '+%m/%d %I:%M %a'","r");
   fgets(buf,sizeof(buf),fp);
   pclose(fp);
   return buf;
}

char*get_ip()
{
   FILE *fp;
   char tmp[16];
   static char buf[16];
   fp = popen("ifconfig ppp0|grep \"inet addr\"|cut -d \":\" -f2|cut -d \" \" -f1","r");
   fgets(tmp,sizeof(buf),fp);
   pclose(fp);
   sprintf(buf,"%16s",tmp);
   return buf;
}


char*get_rx()
{
float f,s,rx;
FILE *fp;
static char buf[16]="                ";
fp = popen("cat /proc/net/dev|grep \"ppp0\"|cut -d \" \" -f4","r");
fgets(buf,sizeof(buf),fp);
pclose(fp);
f=atof(buf);

sleep(1);

fp = popen("cat /proc/net/dev|grep \"ppp0\"|cut -d \" \" -f4","r");
fgets(buf,sizeof(buf),fp);
pclose(fp);
s=atof(buf);

rx = ((s-f)/1024.00);
sprintf(buf," RX:%7.2f KB/s",rx);
return buf;
}


char*get_tx()
{
float f,s,tx;
FILE *fp;
static char buf[16]="                ";
fp = popen("cat /proc/net/dev|grep \"ppp0\"|cut -d \" \" -f42","r");
fgets(buf,sizeof(buf),fp);
pclose(fp);
f=atof(buf);

sleep(1);

fp = popen("cat /proc/net/dev|grep \"ppp0\"|cut -d \" \" -f42","r");
fgets(buf,sizeof(buf),fp);
pclose(fp);
s=atof(buf);

tx = ((s-f)/1024.00);
sprintf(buf," TX:%7.2f KB/s",tx);
return buf;
}

 
  




你可能感兴趣的:(linux,shell)