【问题标题】:Reading console output for ping in C在 C 中读取控制台输出以进行 ping
【发布时间】:2020-01-20 14:58:10
【问题描述】:

我目前正在尝试编写一些 ping 不同 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;
}

【问题讨论】:

  • 您可以使用popen()而不是system()来读取父进程中的命令输出
  • 好的,我如何访问我感兴趣的输出中的位(在这种情况下是“x% 丢包”?
  • 使用标准 C 字符串函数
  • 为什么? ping 返回一个合理的退出值,系统返回。不解析输出,只检查返回值。

标签: c linux string ping


【解决方案1】:

如果您对粗略的可用性监视器感兴趣,可以通过 <sys/wait.h> 中的宏检查 ping 的退出值

#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 中的 popen() 示例非常中肯:

#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() */
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多