log_kmsg.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Kernel log pane source: follows /dev/kmsg from the moment it is opened. */
  2. #include <errno.h>
  3. #include <fcntl.h>
  4. #include <glib-unix.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include "app.h"
  8. struct log_kmsg {
  9. int fd;
  10. guint watch_id;
  11. mpdc_log_fn log;
  12. void *user;
  13. };
  14. static gboolean on_kmsg(gint fd, GIOCondition cond, gpointer data)
  15. {
  16. struct log_kmsg *k = data;
  17. char buf[4096];
  18. ssize_t n;
  19. (void)cond;
  20. for (;;) {
  21. char *text, *end;
  22. n = read(fd, buf, sizeof(buf) - 1);
  23. if (n < 0 && errno == EPIPE)
  24. continue; /* records were overwritten; carry on */
  25. if (n <= 0)
  26. break;
  27. buf[n] = '\0';
  28. /* "prio,seq,usec,flags;message\n" then optional " KEY=value" lines */
  29. text = strchr(buf, ';');
  30. if (!text)
  31. continue;
  32. text++;
  33. end = strchr(text, '\n');
  34. if (end)
  35. *end = '\0';
  36. k->log(k->user, text);
  37. }
  38. if (n == 0 || (n < 0 && errno != EAGAIN)) {
  39. k->watch_id = 0;
  40. return G_SOURCE_REMOVE;
  41. }
  42. return G_SOURCE_CONTINUE;
  43. }
  44. struct log_kmsg *log_kmsg_new(mpdc_log_fn log, void *user)
  45. {
  46. struct log_kmsg *k = g_new0(struct log_kmsg, 1);
  47. k->log = log;
  48. k->user = user;
  49. k->fd = open("/dev/kmsg", O_RDONLY | O_NONBLOCK | O_CLOEXEC);
  50. if (k->fd < 0) {
  51. log(user, "Nie można otworzyć /dev/kmsg");
  52. return k;
  53. }
  54. lseek(k->fd, 0, SEEK_END);
  55. k->watch_id = g_unix_fd_add(k->fd, G_IO_IN, on_kmsg, k);
  56. return k;
  57. }
  58. void log_kmsg_free(struct log_kmsg *k)
  59. {
  60. if (k->watch_id)
  61. g_source_remove(k->watch_id);
  62. if (k->fd >= 0)
  63. close(k->fd);
  64. g_free(k);
  65. }