1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| #include <glib.h>
typedef struct _MySource MySource;
struct _MySource { GSource _source; GIOChannel *channel; GPollFD fd; }; static gboolean prepare(GSource *source, gint *timeout) { *timeout = -1; return FALSE; } static gboolean check(GSource *source) { MySource *mysource = (MySource *)source;
if(mysource->fd.revents != mysource->fd.events) return FALSE;
return TRUE; } static gboolean dispatch(GSource *source, GSourceFunc callback, gpointer user_data) { MySource *mysource = (MySource *)source;
if(callback) callback(mysource->channel);
return TRUE; } static void finalize(GSource *source) { MySource *mysource = (MySource *)source;
if(mysource->channel) g_io_channel_unref(mysource->channel); } static gboolean watch(GIOChannel *channel) { gsize len = 0; gchar *buffer = NULL; g_io_channel_read_line(channel, &buffer, &len, NULL, NULL); if(len > 0) g_print("%d\n", len-1); g_free(buffer);
return TRUE; } gboolean io_watch(GIOChannel *channel, GIOCondition condition, gpointer data) { gsize len = 0; gchar *buffer = NULL;
g_io_channel_read_line(channel, &buffer, &len, NULL, NULL); if(len > 0) g_print("%d\n", len-1); g_free(buffer);
return TRUE; }
int main01(){ GMainLoop *loop = g_main_loop_new(NULL, FALSE); GSourceFuncs funcs = {prepare, check, dispatch, finalize}; GSource *source = g_source_new(&funcs, sizeof(MySource)); MySource *mysource = (MySource *)source;
mysource->channel = g_io_channel_new_file("/machine/test.txt", "r", NULL); if(mysource->channel == NULL){ g_printerr("fail to read file"); } mysource->fd.fd = g_io_channel_unix_get_fd(mysource->channel); mysource->fd.events = G_IO_IN; g_source_add_poll(source, &mysource->fd); g_source_set_callback(source, (GSourceFunc)watch, NULL, NULL); g_source_set_priority(source, G_PRIORITY_DEFAULT_IDLE); g_source_attach(source, NULL); g_source_unref(source);
g_main_loop_run(loop);
g_main_context_unref(g_main_loop_get_context(loop)); g_main_loop_unref(loop);
return 0; }
int main(){ GMainLoop *loop = g_main_loop_new(NULL, FALSE);
g_print("input string: \n"); GIOChannel* channel = g_io_channel_unix_new(1); if(channel) { g_io_add_watch(channel, G_IO_IN, io_watch, NULL); g_io_channel_unref(channel); }
g_main_loop_run(loop);
g_main_context_unref(g_main_loop_get_context(loop)); g_main_loop_unref(loop);
return 0; }
|