help icon indicating copy to clipboard operation
help copied to clipboard

Reading a file synchronously

Open packetq opened this issue 7 years ago • 4 comments
trafficstars

Hello All,

I'm trying to read a file synchronously, uv_fs_read returns EFAULT. Is there something wrong with my code?

`uv_fs_t open_req; uv_fs_t close_req; uv_fs_t read_req; int ret = 0; uv_buf_t buffer; unsigned int len = 1000*sizeof(char);

char *base = (char *)malloc(len); buffer = uv_buf_init(base, len);

ret = uv_fs_open(NULL, &open_req, "/tmp/test.txt", O_RDWR, 0644, NULL);

if(ret < 0) { fprintf(stderr, "error opening file: %s\n", uv_strerror((int)open_req.result)); return(false); }

ret = uv_fs_read(NULL, &read_req, open_req.result, buffer.base, buffer.len, 0, NULL);

if(ret < 0) { fprintf(stderr, "error reading file: %s-%s\n", uv_err_name(ret), uv_strerror((int)read_req.result)); return(false); }

uv_fs_close(NULL, &close_req, open_req.result, NULL);

free(buffer.base);`

Thanks, -G

packetq avatar Sep 26 '18 12:09 packetq

Have you tried it with a non-NULL uv_loop_t?

davisjam avatar Sep 26 '18 12:09 davisjam

Yes. I have tried with a loop. It doesn't seem to make any difference.There are actually several places in the library source that do this. Unfortunately, I haven't had time to decipher the whole INIT/POST thing yet.

packetq avatar Sep 26 '18 18:09 packetq

uv_fs_read --> preadv --> errors as from read and lseek.

EFAULT is listed as an error for read:

EFAULT
    buf is outside your accessible address space.

The signature for uv_fs_read is:

int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb)

You are calling it as:

ret = uv_fs_read(NULL, &read_req, open_req.result, buffer.base, buffer.len, 0, NULL);

I haven't tried your code, but it looks like instead of bufs, nbufs (4th and 5th args) you are providing the address of your buffer base and the length of that buffer.

Do you think something like this is what you should be providing?

ret = uv_fs_read(NULL, &read_req, open_req.result, &buffer, 1, 0, NULL);

davisjam avatar Sep 26 '18 18:09 davisjam

That's the ticket!

Thanks, -G

packetq avatar Sep 26 '18 19:09 packetq