Tizen 2.1 base
[framework/uifw/ecore.git] / src / examples / ecore_fd_handler_example.c
1 #include <Ecore.h>
2 #include <unistd.h>
3
4 struct context
5 {
6    Ecore_Fd_Handler *handler;
7    Ecore_Timer      *timer;
8 };
9
10 static void
11 _fd_prepare_cb(void *data, Ecore_Fd_Handler *handler)
12 {
13    printf("prepare_cb called.\n");
14 }
15
16 static Eina_Bool
17 _fd_handler_cb(void *data, Ecore_Fd_Handler *handler)
18 {
19    struct context *ctxt = data;
20    char buf[1024];
21    size_t nbytes;
22    int fd;
23
24    if (ecore_main_fd_handler_active_get(handler, ECORE_FD_ERROR))
25      {
26         printf("An error has occurred. Stop watching this fd and quit.\n");
27         ecore_main_loop_quit();
28         ctxt->handler = NULL;
29         return ECORE_CALLBACK_CANCEL;
30      }
31
32    fd = ecore_main_fd_handler_fd_get(handler);
33    nbytes = read(fd, buf, sizeof(buf));
34    if (nbytes == 0)
35      {
36         printf("Nothing to read, exiting...\n");
37         ecore_main_loop_quit();
38         ctxt->handler = NULL;
39         return ECORE_CALLBACK_CANCEL;
40      }
41    buf[nbytes - 1] = '\0';
42
43    printf("Read %zd bytes from input: \"%s\"\n", nbytes - 1, buf);
44
45    return ECORE_CALLBACK_RENEW;
46 }
47
48 static Eina_Bool
49 _timer_cb(void *data)
50 {
51    printf("Timer expired after 5 seconds...\n");
52
53    return ECORE_CALLBACK_RENEW;
54 }
55
56 int
57 main(int argc, char **argv)
58 {
59    struct context ctxt = {0};
60
61    if (!ecore_init())
62      {
63         printf("ERROR: Cannot init Ecore!\n");
64         return -1;
65      }
66
67    ctxt.handler = ecore_main_fd_handler_add(STDIN_FILENO,
68                                             ECORE_FD_READ | ECORE_FD_ERROR,
69                                             _fd_handler_cb,
70                                             &ctxt, NULL, NULL);
71    ecore_main_fd_handler_prepare_callback_set(ctxt.handler, _fd_prepare_cb, &ctxt);
72    ctxt.timer = ecore_timer_add(5, _timer_cb, &ctxt);
73
74    printf("Starting the main loop. Type anything and hit <enter> to "
75           "activate the fd_handler callback, or CTRL+d to shutdown.\n");
76
77    ecore_main_loop_begin();
78
79    if (ctxt.handler)
80      ecore_main_fd_handler_del(ctxt.handler);
81
82    if (ctxt.timer)
83      ecore_timer_del(ctxt.timer);
84
85    ecore_shutdown();
86
87    return 0;
88 }
89