Linux管道:通过popen捕获ping的实时输出

时间:2023-02-04 14:04:26

Linux/C/pipes:

How can I capture the output of ping command using popen(Or similar system calls). Currently popen will wait until ping is finished. Then output will be dumped together.

如何使用popen(或类似的系统调用)捕获ping命令的输出。目前popen将等待ping完成。然后输出将被转储。

Pseudo code:

fp= popen("ping x.x.x.x", "r");
while(!feof(pFp))
{
   if(fgets(fp ...) // <==currently the code blocks here until ping finishes in popen
   { 
       printf(...real time ping output here);
   }
}

1 个解决方案

#1


7  

It's not waiting until ping is finished. Rather, ping is waiting until the stdout buffer fills up before writing anything. The only ways to avoid this involve pseudo-ttys. Either you should abandon popen and write the code to run the ping child process yourself and use a pseudo-tty to communicate (this is easy with the nonstandard but widely available forkpty function) or you could write a wrapper program that runs ping through a pseudo-pty and grabs the output, and writes it without buffering to stdout.

它不会等到ping结束。相反,ping正在等待,直到stdout缓冲区填满之后才写入任何东西。避免这种情况的唯一方法涉及伪ttys。要么你应该放弃popen并编写代码来自己运行ping子进程并使用伪tty进行通信(这对于非标准但广泛使用的forkpty函数很容易)或者你可以编写一个通过伪运行ping的包装器程序-pty并获取输出,并将其写入而不缓冲到stdout。

#1


7  

It's not waiting until ping is finished. Rather, ping is waiting until the stdout buffer fills up before writing anything. The only ways to avoid this involve pseudo-ttys. Either you should abandon popen and write the code to run the ping child process yourself and use a pseudo-tty to communicate (this is easy with the nonstandard but widely available forkpty function) or you could write a wrapper program that runs ping through a pseudo-pty and grabs the output, and writes it without buffering to stdout.

它不会等到ping结束。相反,ping正在等待,直到stdout缓冲区填满之后才写入任何东西。避免这种情况的唯一方法涉及伪ttys。要么你应该放弃popen并编写代码来自己运行ping子进程并使用伪tty进行通信(这对于非标准但广泛使用的forkpty函数很容易)或者你可以编写一个通过伪运行ping的包装器程序-pty并获取输出,并将其写入而不缓冲到stdout。