gpt4 book ai didi

c++ - Linux 管道 : Capturing realtime output of ping via popen

转载 作者:IT王子 更新时间:2023-10-29 00:50:30 26 4
gpt4 key购买 nike

Linux/C/管道:

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

伪代码:

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);
}
}

最佳答案

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

关于c++ - Linux 管道 : Capturing realtime output of ping via popen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6535284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com