Skip to content

Instantly share code, notes, and snippets.

@bert
Created December 19, 2009 14:19
Show Gist options
  • Save bert/260094 to your computer and use it in GitHub Desktop.
Save bert/260094 to your computer and use it in GitHub Desktop.
GIOChannel based command system example
/*!
* \file main.c
* \brief
*/
#include <glib.h>
#include <glib/gprintf.h>
#include <gio/gio.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static void
prompt ()
{
g_printf ("myprompt> ");
}
static void
handlecommand (gchar *sz)
{
g_printf ("You typed: %s", sz);
prompt();
}
static gboolean
mycallback (GIOChannel *channel, GIOCondition cond, gpointer data)
{
gchar *str_return;
gsize length;
gsize terminator_pos;
GError *error = NULL;
if (g_io_channel_read_line (channel, &str_return, &length, &terminator_pos, &error) == G_IO_STATUS_ERROR)
{
g_warning ("Something went wrong");
}
if (error != NULL)
{
g_printf (error->message);
exit(1);
}
handlecommand (str_return);
g_free( str_return );
return TRUE;
}
int
main (int argc, char* argv[])
{
GError **error = NULL;
GMainLoop *mainloop = g_main_loop_new (NULL, FALSE);
#ifdef G_OS_WIN32
GIOChannel *channel = g_io_channel_win32_new_fd (STDIN_FILENO);
#else
GIOChannel *channel = g_io_channel_unix_new (STDIN_FILENO);
#endif
g_io_channel_set_encoding (channel, NULL, error);
prompt ();
g_io_add_watch (channel, G_IO_IN, mycallback, NULL);
g_main_loop_run (mainloop);
return 0;
}
/* EOF */
CFLAGS = -Wall -g `pkg-config --cflags --libs gio-2.0 gtk+-2.0`
LDFLAGS = `pkg-config --cflags --libs gio-2.0 gtk+-2.0`
all: \
command
command: main.c
$(CC) -o command main.c $(CFLAGS)
clean:
rm -f *~
rm -f *.o
rm -f command
@ccoupe
Copy link

ccoupe commented Jul 16, 2016

Thanks for posting this example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment