ecore_fd_handler_example.c

This example shows how to setup and use an fd_handler. See the explanation here.

/*
* gcc -o ecore_fd_handler_example ecore_fd_handler_example.c `pkg-config --cflags --libs ecore`
*/
#include <Ecore.h>
#include <unistd.h>
struct context
{
Ecore_Fd_Handler *handler;
Ecore_Timer *timer;
};
static void
_fd_prepare_cb(void *data EINA_UNUSED, Ecore_Fd_Handler *handler EINA_UNUSED)
{
printf("prepare_cb called.\n");
}
static Eina_Bool
_fd_handler_cb(void *data, Ecore_Fd_Handler *handler)
{
struct context *ctxt = data;
char buf[1024];
size_t nbytes;
int fd;
{
printf("An error has occurred. Stop watching this fd and quit.\n");
ctxt->handler = NULL;
}
nbytes = read(fd, buf, sizeof(buf));
if (nbytes == 0)
{
printf("Nothing to read, exiting...\n");
ctxt->handler = NULL;
}
buf[nbytes - 1] = '\0';
printf("Read %zd bytes from input: \"%s\"\n", nbytes - 1, buf);
}
static Eina_Bool
_timer_cb(void *data EINA_UNUSED)
{
printf("Timer expired after 5 seconds...\n");
}
int
main(void)
{
struct context ctxt = {0};
if (!ecore_init())
{
printf("ERROR: Cannot init Ecore!\n");
return -1;
}
ctxt.handler = ecore_main_fd_handler_add(STDIN_FILENO,
_fd_handler_cb,
&ctxt, NULL, NULL);
ecore_main_fd_handler_prepare_callback_set(ctxt.handler, _fd_prepare_cb, &ctxt);
ctxt.timer = ecore_timer_add(5, _timer_cb, &ctxt);
printf("Starting the main loop. Type anything and hit <enter> to "
"activate the fd_handler callback, or CTRL+d to shutdown.\n");
if (ctxt.handler)
if (ctxt.timer)
ecore_timer_del(ctxt.timer);
return 0;
}