Skip to content

Instantly share code, notes, and snippets.

@kbridge
Last active February 11, 2019 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbridge/3bfa794b28e916d650b4cfe623ee6ede to your computer and use it in GitHub Desktop.
Save kbridge/3bfa794b28e916d650b4cfe623ee6ede to your computer and use it in GitHub Desktop.
uv different behavior under windows/linux
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
#include <chrono>
#include <thread>
using std::chrono::seconds;
using std::this_thread::sleep_for;
uv_fs_t open_req;
uv_fs_t read_req;
uv_buf_t iov;
char buffer[1024];
uv_check_t check_handle;
uv_idle_t idle_handle;
void on_check(uv_check_t *h)
{
puts("check");
}
void on_idle(uv_idle_t *h)
{
puts("idle");
uv_check_start(&check_handle, on_check);
}
void on_read(uv_fs_t *req)
{
if (req->result < 0) {
fprintf(stderr, "read file fail: %s\n", uv_strerror((int)req->result));
return;
}
if (req->result == 0) {
uv_fs_t close_req;
uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
return;
}
buffer[req->result] = '\0';
printf("len=%d '%s'\n", req->result, buffer);
uv_idle_stop(&idle_handle);
uv_check_stop(&check_handle);
}
void on_open(uv_fs_t *req)
{
if (req->result < 0) {
fprintf(stderr, "open file fail: %s\n", uv_strerror((int)req->result));
return;
}
uv_idle_start(&idle_handle, on_idle);
iov = uv_buf_init(buffer, sizeof buffer);
uv_fs_read(uv_default_loop(), &read_req, req->result, &iov, 1, -1, on_read);
puts("read start");
sleep_for(seconds(2));
}
int main()
{
uv_idle_init(uv_default_loop(), &idle_handle);
uv_check_init(uv_default_loop(), &check_handle);
// you need to create 1.txt first:
//
// echo 123 >1.txt
//
uv_fs_open(uv_default_loop(), &open_req, "1.txt", O_RDONLY, 0, on_open);
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
uv_fs_req_cleanup(&open_req);
uv_fs_req_cleanup(&read_req);
return 0;
}
@kbridge
Copy link
Author

kbridge commented Feb 11, 2019

You need to create 1.txt first.

On Windows, it prints:

read start
idle
check
len=3 'xxx'

On Linux, it prints:

read start
idle
len=3 'xxx'

(Lacking check is due to L47 canceling the handler.)

Why their behaviors differ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment