examples/reference/c/core/src/core_loop.c

139 lines
3.0 KiB
C

#define EFL_BETA_API_SUPPORT 1
#include <stdio.h>
#include <Eina.h>
#include <Efl_Core.h>
#define FILENAME "/tmp/core_loop_test.txt"
/*
* Efl Core Loop examples.
*
* A collection of loop examples. First we print out loop information and
* show how loops are inherited.
*
* Then we move on to the Efl.Loop.Fd and show how you could use a loop to
* read or write to an FD without blocking.
*/
static void _read_fd_create();
static void
_print_loop(Efl_Loop *loop, const char *label)
{
printf("%s loop found at %p \"%s\"\n", label, loop, efl_name_get(loop));
}
static void
_read_fd_cb(void *data EINA_UNUSED, const Efl_Event *event)
{
Efl_Loop_Fd *fd_obj;
char buf[7];
int len;
fd_obj = event->object;
len = read(efl_loop_fd_file_get(fd_obj), &buf, sizeof(buf));
// here we are exiting
if (len <= 0)
{
efl_unref(fd_obj);
unlink(FILENAME);
efl_exit(0);
return;
}
buf[len] = 0;
printf("Reading from: %s\n", efl_name_get(fd_obj));
}
static void
_write_fd_cb(void *data EINA_UNUSED, const Efl_Event *event)
{
Efl_Loop_Fd *fd_obj;
static int _count = 0;
fd_obj = event->object;
// we have output all we wanted, remove the write handler
// and start checking for read availability instead
if (_count >= 5)
{
efl_unref(fd_obj);
_read_fd_create();
return;
}
_count++;
printf("Writing to: %s\n", efl_name_get(fd_obj));
write(efl_loop_fd_file_get(fd_obj), eina_slstr_printf("TEST %d\n", _count), 7);
}
static void
_write_fd_create()
{
Efl_Loop_Fd *fd_obj;
FILE *file;
int fd;
fd_obj = efl_new(EFL_LOOP_FD_CLASS,
efl_name_set(efl_added, "Write FD"));
efl_event_callback_add(fd_obj, EFL_LOOP_FD_EVENT_WRITE, _write_fd_cb, NULL);
file = fopen(FILENAME, "w+");
fd = fileno(file);
printf("Opened file %s with fd %d\n", FILENAME, fd);
efl_loop_fd_file_set(fd_obj, fd);
}
static void
_read_fd_create()
{
Efl_Loop_Fd *fd_obj;
FILE *file;
int fd;
fd_obj = efl_new(EFL_LOOP_FD_CLASS,
efl_name_set(efl_added, "Read FD"));
efl_event_callback_add(fd_obj, EFL_LOOP_FD_EVENT_READ, _read_fd_cb, NULL);
file = fopen(FILENAME, "r");
fd = fileno(file);
printf("Opened file %s with fd %d\n", FILENAME, fd);
efl_loop_fd_file_set(fd_obj, fd);
}
EAPI_MAIN void
efl_main(void *data EINA_UNUSED, const Efl_Event *ev)
{
const Efl_Version *version;
Efl_Loop *loop;
loop = ev->object;
version = efl_app_efl_version_get(loop);
printf("Running on EFL version %d.%d.%d [%s]\n\n", version->major, version->minor,
version->micro, version->build_id);
_print_loop(loop, "Application");
loop = efl_add(EFL_LOOP_CONSUMER_CLASS, loop,
efl_name_set(efl_added, "Loop Consumer"));
_print_loop(loop, "Child");
efl_del(loop);
printf("\n");
_write_fd_create();
// we will call _read_fd_create() once write is complete!
// we will exit from the end of the read loop
}
EFL_MAIN()