Blame docs/code/idle-compute/main.c

Packit b5b901
#include <stdio.h>
Packit b5b901
Packit b5b901
#include <uv.h>
Packit b5b901
Packit b5b901
uv_loop_t *loop;
Packit b5b901
uv_fs_t stdin_watcher;
Packit b5b901
uv_idle_t idler;
Packit b5b901
char buffer[1024];
Packit b5b901
Packit b5b901
void crunch_away(uv_idle_t* handle) {
Packit b5b901
    // Compute extra-terrestrial life
Packit b5b901
    // fold proteins
Packit b5b901
    // computer another digit of PI
Packit b5b901
    // or similar
Packit b5b901
    fprintf(stderr, "Computing PI...\n");
Packit b5b901
    // just to avoid overwhelming your terminal emulator
Packit b5b901
    uv_idle_stop(handle);
Packit b5b901
}
Packit b5b901
Packit b5b901
void on_type(uv_fs_t *req) {
Packit b5b901
    if (stdin_watcher.result > 0) {
Packit b5b901
        buffer[stdin_watcher.result] = '\0';
Packit b5b901
        printf("Typed %s\n", buffer);
Packit b5b901
Packit b5b901
        uv_buf_t buf = uv_buf_init(buffer, 1024);
Packit b5b901
        uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type);
Packit b5b901
        uv_idle_start(&idler, crunch_away);
Packit b5b901
    }
Packit b5b901
    else if (stdin_watcher.result < 0) {
Packit b5b901
        fprintf(stderr, "error opening file: %s\n", uv_strerror(req->result));
Packit b5b901
    }
Packit b5b901
}
Packit b5b901
Packit b5b901
int main() {
Packit b5b901
    loop = uv_default_loop();
Packit b5b901
Packit b5b901
    uv_idle_init(loop, &idler);
Packit b5b901
Packit b5b901
    uv_buf_t buf = uv_buf_init(buffer, 1024);
Packit b5b901
    uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type);
Packit b5b901
    uv_idle_start(&idler, crunch_away);
Packit b5b901
    return uv_run(loop, UV_RUN_DEFAULT);
Packit b5b901
}