在 C 中使用 popen 调用 ping

Calling ping using popen in C

我在 CentOS linux 中的 C 代码中有以下代码。此代码在线程中每 5 秒调用一次。如果我禁用 pclose(fp),代码工作正常,但我知道我应该这样做。有人可以解释为什么当我启用它时它会挂在 pclose(fp) 吗? 非常感谢。

FILE* fp;
int status;
char path[255];

fp = popen("ping -c 3 -W 3 200.0.0.51", "r");
sleep(3); 
int i=0; 
while (i < 255) {
    path[i] = fgetc(fp); 
    i++;
}

char* str;
str = strstr(path, "100% packet loss");

if (str!=NULL) {
    //pclose(fp); // <--- hangs here if I enable
    OS_Reboot(); 
}

问题似乎是 pclose() 只有 returns 当从 popen 创建的进程终止时,但 ping 一直在循环。

In any case, pclose() shall not return before the child process created by popen() has terminated

一个解决方案是自己分叉进程并为返回到您的进程的标准输入和标准输出创建管道。 here 另一个 Whosebug 成员显示了此的可能实现。

发布的代码在启用 pclose 的情况下对我来说工作正常(我还删除了分支以确保它会被调用)。请注意 "The pclose() function waits for the associated process to terminate and returns the exit status of the command as returned by wait4(2)" (from the docs) 所以可能 "ping -c 3 -W 3 200.0.0.51" 实际上挂在您的机器上(不知道为什么会这样)。

您看到的行为应该只在 ping 没有终止的情况下发生,在您的情况下,由于 -c 3.

,在发送三个数据包后应该会发生这种情况

您或许应该将 -n 添加到调用中,以避免在连接中断时卡在 DNS 查找上?