linux c读取shell输出
2021/11/7 7:12:50
本文主要是介绍linux c读取shell输出,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
使用popen()
示例1
#include <stdio.h> int main(int argc, char *argv[]) { FILE *fp; char buffer[80]; fp=popen("cat /etc/passwd", "r"); fgets(buffer,sizeof(buffer),fp); printf("%s",buffer); return 0; }
示例2
读取EC20的GPS坐标
int my_strcmp(char *s1, char *s2, int len) { int i; for(i = 0; i < len; i++) { if(s1[i] != s2[i]) return 0; } return 1; } char *my_strfind(char *buf, char *s, char s_len, int len) { int i,j,tmp; //printf("buf %s s %s len %d\n",buf,s,len); //printf("slen %d\n", sizeof(s)); for(i = 0; i < len; i++) { tmp = my_strcmp(&buf[i], s, s_len); if(tmp == 1) { //printf("cmp ok\n"); return &buf[i]; } } return 0; } char *my_strcpy(char *s1, char *s2, char end) { int i; for(i = 0; i < 20; i++) { if(s2[i] == end) break; s1[i] = s2[i]; } return &s2[i]; } int gps_get(char *buf, int len, char *longitude, char *latitude) { const char GPS_HEAD[] = "$GPRMC"; char i = 0,j = 0,*cur; int ret = 0; cur = my_strfind(buf, (char *)GPS_HEAD, 6, (1024 - sizeof(GPS_HEAD))); //printf("cur = %c\n",*cur); if(cur != 0) { cur = my_strfind(cur, "A,", 2, 60); //printf("cur = %c\n",*cur); if(cur != 0) { //printf("cur = %c\n",*cur); cur = my_strcpy(latitude, (cur+2), ','); //printf("cur = %c\n",*cur); cur = my_strcpy(longitude, (cur+3), ','); } } return 0; } int read_gps(float *lon, float *lat) { static char state = 0,serial_buff[1024] = {0}, lon_tmp[20] = {0}, lat_tmp[20] = {0}; int ret = 0,Gps_fd = 0; float tmp[2]; FILE *fp; if(state == 0) { system("echo -e \"AT+QGPS=1\r\n\" > /dev/ttyUSB2");//open gps state = 1; } else { fp=popen("cat /dev/ttyUSB1", "r"); fread(serial_buff, sizeof(char), 1024, fp); ret = strlen(serial_buff); //printf(serial_buff); if(ret > 1) { ret = gps_get(serial_buff, 1024, lon_tmp, lat_tmp); if(ret == 0) { ret = sscanf(lon_tmp, "%f", &tmp[0]); tmp[1] = (unsigned int)(tmp[0]/100); tmp[0] = ((tmp[0]/100.0) - tmp[1])*100/60; *lon = tmp[0] + tmp[1]; ret = sscanf(lat_tmp, "%f", &tmp[0]); tmp[1] = (unsigned int)(tmp[0]/100); tmp[0] = ((tmp[0]/100.0) - tmp[1])*100/60; *lat = tmp[0] + tmp[1]; //printf("\ngps %f %f\n", *lon, *lat); } } memset(serial_buff, 0, 1024); memset(lon_tmp, 0, 20); memset(lat_tmp, 0, 20); } return 0; }
这篇关于linux c读取shell输出的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-12如何创建可引导的 ESXi USB 安装介质 (macOS, Linux, Windows)
- 2024-11-08linux的 vi编辑器中搜索关键字有哪些常用的命令和技巧?-icode9专业技术文章分享
- 2024-11-08在 Linux 的 vi 或 vim 编辑器中什么命令可以直接跳到文件的结尾?-icode9专业技术文章分享
- 2024-10-22原生鸿蒙操作系统HarmonyOS NEXT(HarmonyOS 5)正式发布
- 2024-10-18操作系统入门教程:新手必看的基本操作指南
- 2024-10-18初学者必看:操作系统入门全攻略
- 2024-10-17操作系统入门教程:轻松掌握操作系统基础知识
- 2024-09-11Linux部署Scrapy学习:入门级指南
- 2024-09-11Linux部署Scrapy:入门级指南
- 2024-08-21【Linux】分区向左扩容的方法