C ++:来自管道的read() - 随机EINTR和EACCESS错误

时间:2014-01-25 19:20:28

标签: c++ fork pipe

我正在尝试在C ++中使用管道和分支。我使用下面的函数来读取和写入管道。它几乎总是按预期工作,除了我有时(随机)获得nbytes = -1,errno = 4(EINTR,系统中断)或nbytes = 0,errno = 13(EACCESS,访问被拒绝)。

当我得到(nbytes,errno)=(-1,4)时,我可以睡几个毫秒,尝试再读一遍并希望得到消息吗?

同样的问题(nbytes,errno)=(0,13)?如果没有,我随机获取访问权限的原因是什么?

另外,据我所知,有可能获得nbytes> 0但小于预期的字符数nb。在这种情况下,readbuffer会包含不完整的消息吗?我可以再次使用缺少的char来调用read()来获取其余的吗?

int size_digits = 10;
void read_from_pipe (int file, std::istringstream & is)
{
    char readbuffer[size_digits];
    // Receive size of the message first
    int nbytes = read(file, readbuffer, size_digits);
    if(nbytes != size_digits){
        std::ostringstream oss;
        oss << "Failed when reading from pipe - nbytes:" << nbytes << ", size_digits:" << size_digits << ", errno: " << errno;
        throw(oss.str());
    }
    int buffer_size = atoi(readbuffer);
    char readbuffer2[buffer_size];
    nbytes = read(file, readbuffer2, buffer_size);
    if(nbytes != buffer_size){
        std::ostringstream oss;
        oss << "Failed when reading from pipe - nbytes:" << nbytes << ", buffer_size:" << buffer_size << ", errno: " << errno;
        throw(oss.str());
    }
    is.str(readbuffer2);
    return;
}

void
write_to_pipe (int file, std::ostringstream & os)
{
const char* c_str = os.str().c_str();
char writebuffer[size_digits];
sprintf(writebuffer,"%10d", int(strlen(c_str)));
// Send size of the message first
write(file, writebuffer, size_digits);
// Now send the message
write(file, c_str, strlen(c_str));
return;
}

0 个答案:

没有答案