aio_write()始终失败,错误为EINVAL

时间:2014-02-18 04:18:16

标签: c++ posix

我正在尝试使用aio_write(1)函数。下面的代码是我的程序。但是,aio_write()始终返回EINVAL。

我读了EINVAL的错误原因:aio_offset,aio_reqprio,aio_nbytes中的一个或多个无效。但是,我无法弄清楚我设置的值不正确的原因!

有人可以帮忙吗?

[更新] 此代码可编辑且可运行!但结果不正确!我认为这是因为buffer_out在写入文件之前被覆盖了。有没有更好更整洁的方法呢?可以查询aio_error(1),但这就像忙碌等待并损害性能。

有没有更好的方法可以避免缓冲区被覆盖并保持速度?

#include <iostream>
#include <cstring>
#include <aio.h>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <errno.h>
using namespace std;

#define true 1
#define false 0

int main()
{
    int i = 0;
    int offset = 0, fd_offset = 0;
    int slen = 0;
    char* buffer, *buffer_out;
    int buffer_size = 30;
    int is_first_write = true;

    struct aiocb aio_param;
    int fd_out = open("result.log", O_APPEND | O_RDWR);    

    buffer = (char*) malloc(buffer_size);
    buffer_out = (char*) malloc(buffer_size);
    memset(buffer, 0, buffer_size);
    memset(buffer_out, 0, buffer_size);

    for( i = 0; i < 10; i++)
    {
        stringstream ss;
        ss << "LOG *****" << i << "-" << "********\n";
        slen = strlen(ss.str().c_str());
        //cout<<"written to offset: " << offset << endl; 
        //buffer is not large enough to take the current string
        if(offset + slen > buffer_size)
        {
        //write the current buffer content (< 4K) into the file
            memset(&aio_param, 0, sizeof(aio_param));
            aio_param.aio_fildes = fd_out;
            aio_param.aio_offset = fd_offset;
            while( aio_error(&aio_param) != 0 && is_first_write == false ) {cout << "wait for the previous one finish" <<endl;}
            aio_param.aio_buf = memcpy(buffer_out, buffer, buffer_size); //the buffer_out has to be written before it's copied to again!
            aio_param.aio_nbytes = offset;
            //aio_offset = ? should be the end of file for O_APPEND mode
            aio_param.aio_sigevent.sigev_notify = SIGEV_NONE;
            if( aio_write(&aio_param) == -1 )
            {
                cout<<"ERR: aio_write()==-1"<<endl;
                cout<<"errno:" << errno <<endl;
                return 1;
            }else{
                is_first_write = false;
                fd_offset += offset;
                cout<<"aio_write()" << offset << " bytes succeed at file offset " << fd_offset<<endl;
                offset = 0;
             //   sleep(1);
            //clean the buffer
                memset(buffer, 0, buffer_size);
            }
        }
        //write the current string to the buffer 
        memcpy(buffer + offset, ss.str().c_str(), slen);
        offset += slen;
    }
    close(fd_out);
    return 0;

}

错误的结果是:

LOG *****2-********
LOG *****4-********
LOG *****4-********
LOG *****4-********
LOG *****5-********
LOG *****5-********
LOG *****6-********
LOG *****8-********

(应该是0到8之间没有任何重复。)

1 个答案:

答案 0 :(得分:1)

由于您没有分配aio_param的所有值(并且它在堆栈中未初始化),我建议在使用之前将其归零:

memset(&aio_param, 0, sizeof(aio_param));

另外,我想你可能想设置aio_offset