比如说,想看看某个IP是否通:
int ping_ip(const char* ip) { FILE *fstream = NULL; char buffer[1024]; int found = -1; memset(buffer, 0, sizeof(buffer)); //只ping一次 sprintf(buffer, "ping -c 1 %s", ip); if (NULL == (fstream = popen(buffer,"r"))) { return -1; } //读取执行结果 while (NULL != fgets(buffer, sizeof(buffer), fstream)) { //LOG_INFO("%s", buffer); //包含特定字串,表示执行成功 if (strstr(buffer, "bytes from") != NULL) { //找到了 found = 0; break; } } pclose(fstream); return found; }
实际测试中发现,fgets()有时会崩溃。