aboutsummaryrefslogtreecommitdiff
path: root/extras/util/automonitor/automonitor.c
blob: f55e2f4b8ce868226091a87f6980f58658bacf35 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <libudev.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <unistd.h>

#define BLOCK_SIZE 512
#define STRNCMP(s, cs) strncmp(s, cs, strlen(cs))

int execute_shell_script() {
  char *home = getenv("HOME");

  if (!home) {
    fprintf(stderr, "No home environment variable.");
    return 1;
  }

  char script_path[4096];

  snprintf(script_path, sizeof(script_path) - 1,
           "%s/.xmonad/configure-displays", home);

  int f = fork();
  if (f == 0) {
    // child process.
    execl(script_path, script_path, "change", NULL);
    perror("Exec failed");
    exit(1);
  } else {
    if (f == -1) {
      perror("Forking failed");
      return 1;
    } else {
      waitpid(f, NULL, 0);
    }
  }

  return 0;
}

int main() {
  struct udev *udev;
  struct udev_device *dev;
  struct udev_monitor *mon;
  int fd;

  udev = udev_new();
  if (!udev) {
    fprintf(stderr, "Cannot create new udev context\n");
    return 1;
  }

  mon = udev_monitor_new_from_netlink(udev, "udev");
  udev_monitor_filter_add_match_subsystem_devtype(mon, "drm", NULL);
  udev_monitor_enable_receiving(mon);
  fd = udev_monitor_get_fd(mon);

  int found_event = 0;
  while (1) {
    fd_set fds;
    struct timeval to = {0};
    if (found_event) {
      to.tv_usec = 100000;
    }
    int ret;

    FD_ZERO(&fds);
    FD_SET(fd, &fds);

    ret = select(fd + 1, &fds, NULL, NULL, found_event ? &to : NULL);
    if (ret > 0 && FD_ISSET(fd, &fds)) {
      dev = udev_monitor_receive_device(mon);
      if (dev) {
        if (STRNCMP(udev_device_get_action(dev), "change") == 0) {
          printf("I: Change detected.\n");
          found_event = 1;
          // Still need to clean up some trailing detected changes.
        }
      }
    } else if (ret == 0 && found_event) {
      printf("Executing shell script hook.\n");
      if (execute_shell_script()) {
        fprintf(stderr, "Unable to execute shell script.");
      };
      found_event = 0;
    }
  }
}