xref: /netbsd-src/external/mit/libuv/dist/docs/code/idle-compute/main.c (revision 0e552da7216834a96e91ad098e59272b41087480)
1*0e552da7Schristos #include <stdio.h>
2*0e552da7Schristos 
3*0e552da7Schristos #include <uv.h>
4*0e552da7Schristos 
5*0e552da7Schristos uv_loop_t *loop;
6*0e552da7Schristos uv_fs_t stdin_watcher;
7*0e552da7Schristos uv_idle_t idler;
8*0e552da7Schristos char buffer[1024];
9*0e552da7Schristos 
crunch_away(uv_idle_t * handle)10*0e552da7Schristos void crunch_away(uv_idle_t* handle) {
11*0e552da7Schristos     // Compute extra-terrestrial life
12*0e552da7Schristos     // fold proteins
13*0e552da7Schristos     // computer another digit of PI
14*0e552da7Schristos     // or similar
15*0e552da7Schristos     fprintf(stderr, "Computing PI...\n");
16*0e552da7Schristos     // just to avoid overwhelming your terminal emulator
17*0e552da7Schristos     uv_idle_stop(handle);
18*0e552da7Schristos }
19*0e552da7Schristos 
on_type(uv_fs_t * req)20*0e552da7Schristos void on_type(uv_fs_t *req) {
21*0e552da7Schristos     if (stdin_watcher.result > 0) {
22*0e552da7Schristos         buffer[stdin_watcher.result] = '\0';
23*0e552da7Schristos         printf("Typed %s\n", buffer);
24*0e552da7Schristos 
25*0e552da7Schristos         uv_buf_t buf = uv_buf_init(buffer, 1024);
26*0e552da7Schristos         uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type);
27*0e552da7Schristos         uv_idle_start(&idler, crunch_away);
28*0e552da7Schristos     }
29*0e552da7Schristos     else if (stdin_watcher.result < 0) {
30*0e552da7Schristos         fprintf(stderr, "error opening file: %s\n", uv_strerror(req->result));
31*0e552da7Schristos     }
32*0e552da7Schristos }
33*0e552da7Schristos 
main()34*0e552da7Schristos int main() {
35*0e552da7Schristos     loop = uv_default_loop();
36*0e552da7Schristos 
37*0e552da7Schristos     uv_idle_init(loop, &idler);
38*0e552da7Schristos 
39*0e552da7Schristos     uv_buf_t buf = uv_buf_init(buffer, 1024);
40*0e552da7Schristos     uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type);
41*0e552da7Schristos     uv_idle_start(&idler, crunch_away);
42*0e552da7Schristos     return uv_run(loop, UV_RUN_DEFAULT);
43*0e552da7Schristos }
44