Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux pipe : Capturing realtime output of ping via popen

Tags:

c++

c

linux

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.

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);
   }
}
like image 482
Jacob Avatar asked Jun 30 '11 13:06

Jacob


1 Answers

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.

like image 133
R.. GitHub STOP HELPING ICE Avatar answered Sep 28 '22 06:09

R.. GitHub STOP HELPING ICE