我目前正在尝试用不同的IP来编写一些测试。我得到了这些命令的system(),但是我想要读取控制台输出,并基于这个写string(like TEST PASSED/TEST FAILED)。有没有办法做到这一点,而不保存控制台日志文件和读取(似乎太费解)。
下面是我所做的简单代码示例:
switch (choice) {
case 1:
system("ping -c " STR(COUNTER)" -w "STR(TIMER) " " STR(DEI));
printf("----------------------------------------------------\n\n");
break;
case 2:
system("ping -c " STR(COUNTER)" -w "STR(TIMER) " " STR(AURIX));
printf("----------------------------------------------------\n\n");
break;
case 3:
system("ping -c " STR(COUNTER)" -w "STR(TIMER) " " STR(MID2EI));
printf("----------------------------------------------------\n\n");
break;
case 4:
system("ping -c " STR(COUNTER)" -w "STR(TIMER) " " STR(VEI));
printf("----------------------------------------------------\n\n");
break;
case 5:
printf("Quitting...\n");
sleep(1000);
running = false;
break;
default:
printf("Wrong input. Try again.\n");
printf("----------------------------------------------------\n\n");
break;
}发布于 2020-01-20 15:53:49
如果您对粗可用性监视器感兴趣,可以通过来自ping的宏来检查<sys/wait.h>的退出值。
#include <sys/wait.h>
int exit_status = system("ping -c 1 8.8.8.8");
if (WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == 0)
puts("Reachable!");
else
puts("Unreachable");如果您真的想解析输出,那么来自https://pubs.opengroup.org/onlinepubs/009696799/functions/popen.html的https://pubs.opengroup.org/onlinepubs/009696799/functions/popen.html示例非常贴切:
#include <stdio.h>
...
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
while (fgets(path, PATH_MAX, fp) != NULL)
printf("%s", path);
status = pclose(fp);
if (status == -1) {
/* Error reported by pclose() */
...
} else {
/* Use macros described under wait() to inspect `status' in order
to determine success/failure of command executed by popen() */
...
}https://stackoverflow.com/questions/59825884
复制相似问题