Guest User

Untitled

a guest
Jul 15th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. // save to: io.c
  2. // compile as: gcc io.c `pkg-config --cflags --libs glib-2.0`
  3.  
  4.  
  5. #include <glib.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8.  
  9. enum {READFD, WRITEFD, TTLPIPEFDS};
  10. int fd[TTLPIPEFDS];
  11.  
  12.  
  13. gboolean
  14. my_callback (GIOChannel *source, GIOCondition condition, gpointer data)
  15. {
  16. GMainLoop *loop = (GMainLoop *) data;
  17. switch (condition)
  18. {
  19. case G_IO_IN:
  20. {
  21. gchar buf2[100];
  22. memset (buf2, 0, sizeof (buf2));
  23. read (fd[READFD], buf2, sizeof (buf2)); // read the data from the read-end of the pipe
  24. if (buf2[0])
  25. { // output to text file and to stderr
  26. FILE *fp = fopen ("/tmp/test.out", "w+");
  27. fprintf (fp, "%s", buf2);
  28. fclose (fp);
  29. fprintf (stderr, "written to file: '%s'\n", buf2);
  30. }
  31. g_main_loop_quit (loop);
  32. g_io_channel_shutdown (source, TRUE, NULL);
  33. }
  34. break;
  35. }
  36. return FALSE;
  37. }
  38.  
  39.  
  40. gboolean
  41. idle_function (gpointer nil)
  42. {
  43. printf ("printf() test" );
  44. fflush (stdout);
  45. return FALSE; // remove
  46. }
  47.  
  48.  
  49. int
  50. main ()
  51. {
  52. GMainLoop *loop = g_main_loop_new (NULL,FALSE);
  53. GIOChannel *channel;
  54.  
  55. if (pipe (fd) < 0)
  56. return(-1); // make a new pipe
  57. if (dup2 (fd[WRITEFD], fileno (stdout)) < 0)
  58. return(-1); // copy stdout to write-end
  59. close (fd[WRITEFD]);
  60. g_idle_add ((GSourceFunc) idle_function, NULL); // write message to stdout
  61. channel = g_io_channel_unix_new (fd[READFD]); // watch read-end of pipe
  62. g_io_add_watch (channel, G_IO_IN, (GIOFunc) my_callback, loop);
  63. g_main_loop_run (loop);
  64. return 0;
  65. }
  66.  
  67.  
  68. /* EOF */
Add Comment
Please, Sign In to add comment