Reputation: 835
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);
}
}
Upvotes: 6
Views: 2422
Reputation: 215221
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
.
Upvotes: 8