本文介绍了正确的代码 - 非阻塞管与popen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于非阻塞管道有很多问题,但没有可以复制和粘贴(几乎没有更正)和使用的代码示例。

There are tons of questions about non blocking pipes, but there are NO examples of code that can be copy&paste (with little correction) and used.

我得到了这个线程的想法和来源:

I got the idea and sources from this thread:Non-blocking pipe using popen?

但是如何使用呢?在 while cycle?请检查我的更改。是否真的需要使用 errno == EAGAIN &附加标题 #include< cerrno>
如果需要,建议你拥有更好的版本:

But how to use it? At while cycle? Please, review my changes. Is it really need to use errno == EAGAIN & additional header #include <cerrno> ?Suggest you own better version if need:

    FILE *pipe;
    char buff[512];
    if ( !(pipe = popen( command.c_str(), "r")) ) return false;

    int d = fileno(pipe);
    while ( true )
    {
        ssize_t r = read(d, buff, sizeof(buff));
        if (r == -1 && errno == EAGAIN) // really need errno?
            continue;
        else if (r > 0)
            ptr_output->append(buff);
        else
            break;
    }

    pclose(pipe);


推荐答案

如果读取调用返回错误值( -1 errno 设置为 EAGAIN ,表示没有可用数据,因此继续循环再试一次。如果你摆脱了 errno ,错误将被有效地忽略,你的程序可能会崩溃。想象一下,如果你删除它:当读取返回 -1 ,但是说,错误是,破坏(另一端关闭它),你只会继续试图循环并进入一个无限循环。馊主意。

Yes. If the read call returns with the error value (-1) and errno is set to EAGAIN, that means that no data is available, so you continue the loop to try again. If you got rid of the errno, errors would be effectively ignored, and your program would probably crash. Imagine if you did remove it: When read returned -1, but, say, the error was that the pipe was broken (the other end closed it), you would just keep trying to loop and enter an infinite loop. Bad idea.

这篇关于正确的代码 - 非阻塞管与popen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:00