#include <glib.h>
#include <stdio.h>
#include <string.h>
gboolean my_callback(GIOChannel *source, GIOCondition condition, gpointer data)
{
GMainLoop *loop = (GMainLoop *) data;
gchar *buf=NULL;
GError *error = NULL;
switch (condition)
{
case G_IO_IN:
fprintf(stderr, "callback: condition G_IO_IN (%d)\n", condition);
g_io_channel_read_line(source, &buf, NULL, NULL, &error);
if (buf)
{
FILE *fp = fopen("/tmp/test.out", "w+");
fprintf(fp, "%s", buf);
g_free(buf);
fclose(fp);
}
g_main_loop_quit(loop); // kill main loop, i.e., force pgm exit
g_io_channel_shutdown(source,TRUE,NULL); // close channel
break;
case G_IO_OUT:
{
char *str = g_strdup("string OUT via g_io_channel_write_chars()\n");
fprintf(stderr, "callback: condition G_IO_OUT (%d)\n", condition);
g_io_channel_read_line(source, &buf, NULL, NULL, &error);
if (buf)
{
fprintf(stderr, "read on channel returned data (%s)\n", buf);
g_free(buf);
}
else
{
fprintf(stderr, "read on channel returned NO data\n");
}
g_io_channel_write_chars(source, str, strlen(str), NULL, NULL);
g_free(str);
}
break;
case G_IO_PRI:
fprintf(stderr, "callback: condition G_IO_PRI (%d)\n", condition);
break;
case G_IO_ERR:
fprintf(stderr, "callback: condition G_IO_ERR (%d)\n", condition);
break;
case G_IO_HUP:
fprintf(stderr, "callback: condition G_IO_HUP (%d)\n", condition);
break;
case G_IO_NVAL:
fprintf(stderr, "callback: condition G_IO_NVAL (%d)\n", condition);
break;
default:
fprintf(stderr, "callback: unhandled condition (%d)\n", condition);
break;
}
return FALSE;
}
gboolean idle_function(gpointer nil)
{ // write test message to stdout
fprintf(stdout, "test\n" );
return FALSE; // remove
}
int main()
{
GMainLoop *loop = g_main_loop_new(NULL,FALSE);
GIOChannel *channel;
int fd;
g_idle_add((GSourceFunc) idle_function, NULL);
fd = fileno(stdout); // fd = STDOUT_FILENO
channel = g_io_channel_unix_new(fd); // wrap stdout with GIOChannel
g_io_channel_set_encoding(channel, NULL, NULL); // accept binary, allow no buffering
g_io_channel_set_buffered(channel, FALSE); // don't buffer
g_io_add_watch(channel, G_IO_IN,(GIOFunc) my_callback, loop);
// g_io_add_watch(channel, G_IO_IN | G_IO_OUT,(GIOFunc) my_callback, loop);
g_main_loop_run(loop);
return 0;
}