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-12-18git仓库有更新,jenkins 自动触发拉代码怎么配置的?-icode9专业技术文章分享
- 2024-12-18Jenkins webhook 方式怎么配置指定的分支?-icode9专业技术文章分享
- 2024-12-13Linux C++项目实战入门教程
- 2024-12-13Linux C++编程项目实战入门教程
- 2024-12-11Linux部署Scrapy教程:新手入门指南
- 2024-12-11怎么将在本地创建的 Maven 仓库迁移到 Linux 服务器上?-icode9专业技术文章分享
- 2024-12-10Linux常用命令
- 2024-12-06谁看谁服! Linux 创始人对于进程和线程的理解是…
- 2024-12-04操作系统教程:新手入门及初级技巧详解
- 2024-12-04操作系统入门:新手必学指南