Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // save to: io.c
- // compile as: gcc io.c `pkg-config --cflags --libs glib-2.0`
- #include <glib.h>
- #include <stdio.h>
- #include <string.h>
- enum {READFD, WRITEFD, TTLPIPEFDS};
- int fd[TTLPIPEFDS];
- gboolean
- my_callback (GIOChannel *source, GIOCondition condition, gpointer data)
- {
- GMainLoop *loop = (GMainLoop *) data;
- switch (condition)
- {
- case G_IO_IN:
- {
- gchar buf2[100];
- memset (buf2, 0, sizeof (buf2));
- read (fd[READFD], buf2, sizeof (buf2)); // read the data from the read-end of the pipe
- if (buf2[0])
- { // output to text file and to stderr
- FILE *fp = fopen ("/tmp/test.out", "w+");
- fprintf (fp, "%s", buf2);
- fclose (fp);
- fprintf (stderr, "written to file: '%s'\n", buf2);
- }
- g_main_loop_quit (loop);
- g_io_channel_shutdown (source, TRUE, NULL);
- }
- break;
- }
- return FALSE;
- }
- gboolean
- idle_function (gpointer nil)
- {
- printf ("printf() test" );
- fflush (stdout);
- return FALSE; // remove
- }
- int
- main ()
- {
- GMainLoop *loop = g_main_loop_new (NULL,FALSE);
- GIOChannel *channel;
- if (pipe (fd) < 0)
- return(-1); // make a new pipe
- if (dup2 (fd[WRITEFD], fileno (stdout)) < 0)
- return(-1); // copy stdout to write-end
- close (fd[WRITEFD]);
- g_idle_add ((GSourceFunc) idle_function, NULL); // write message to stdout
- channel = g_io_channel_unix_new (fd[READFD]); // watch read-end of pipe
- g_io_add_watch (channel, G_IO_IN, (GIOFunc) my_callback, loop);
- g_main_loop_run (loop);
- return 0;
- }
- /* EOF */
Add Comment
Please, Sign In to add comment