使用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; }