4 * Glib-based networking support functions. Currently this is just for activity callbacks.
6 * Copyright (c) 2009 Nathan Keynes.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
24 struct io_glib_cbinfo {
25 io_callback_t callback;
28 void (*cbdealloc)(void *);
31 static gboolean io_glib_callback( GIOChannel *source, GIOCondition cond, gpointer data )
33 struct io_glib_cbinfo *cbinfo = (struct io_glib_cbinfo *)data;
34 return cbinfo->callback( g_io_channel_unix_get_fd(source), cbinfo->cbdata);
37 static void io_glib_release( void *data )
39 struct io_glib_cbinfo *cbinfo = (struct io_glib_cbinfo *)data;
40 if( cbinfo->cbdealloc ) {
41 cbinfo->cbdealloc( cbinfo->cbdata );
47 * Register a TCP server socket listener on an already open (and listening)
48 * socket. The socket must not have been previously registered.
49 * @return TRUE on success, FALSE on failure.
51 * Defined in netutil.h
53 io_listener_t io_register_tcp_listener( int fd, io_callback_t callback, void *data, void (*dealloc)(void*) )
55 return io_register_listener( fd, callback, data, dealloc );
58 io_listener_t io_register_listener( int fd, io_callback_t callback, void *data, void (*dealloc)(void *) )
60 struct io_glib_cbinfo *cbinfo = malloc( sizeof(struct io_glib_cbinfo) );
61 assert(cbinfo != NULL);
63 cbinfo->callback = callback;
64 cbinfo->cbdata = data;
65 cbinfo->cbdealloc = dealloc;
68 * Note magic here: the watch creates an event source which holds a
69 * reference to the channel. We unref the channel so that the channel then
70 * is automatically released when the event source goes away.
72 GIOChannel *chan = g_io_channel_unix_new(fd);
73 g_io_channel_set_encoding( chan, NULL, NULL );
74 g_io_channel_set_buffered(chan, FALSE);
75 cbinfo->sourceid = g_io_add_watch_full( chan, 0, G_IO_IN, io_glib_callback, cbinfo, io_glib_release );
76 g_io_channel_unref( chan );
81 void io_unregister_listener( io_listener_t data )
83 struct io_glib_cbinfo *cbinfo = (struct io_glib_cbinfo *)data;
84 g_source_remove(cbinfo->sourceid);
.