-static Config pty_cfg;
-static int pty_master_fd, pty_slave_fd;
-static void *pty_frontend;
-static char pty_name[FILENAME_MAX];
-static int pty_signal_pipe[2];
-static int pty_child_pid;
-static int pty_term_width, pty_term_height;
-static int pty_child_dead, pty_finished;
-static int pty_exit_code;
-char **pty_argv;
-int use_pty_argv = TRUE;
+typedef struct pty_tag *Pty;
+
+/*
+ * The pty_signal_pipe, along with the SIGCHLD handler, must be
+ * process-global rather than session-specific.
+ */
+static int pty_signal_pipe[2] = { -1, -1 }; /* obviously bogus initial val */
+
+struct pty_tag {
+ Config cfg;
+ int master_fd, slave_fd;
+ void *frontend;
+ char name[FILENAME_MAX];
+ int child_pid;
+ int term_width, term_height;
+ int child_dead, finished;
+ int exit_code;
+};
+
+/*
+ * We store our pty backends in a tree sorted by master fd, so that
+ * when we get an uxsel notification we know which backend instance
+ * is the owner of the pty that caused it.
+ */
+static int pty_compare_by_fd(void *av, void *bv)
+{
+ Pty a = (Pty)av;
+ Pty b = (Pty)bv;
+
+ if (a->master_fd < b->master_fd)
+ return -1;
+ else if (a->master_fd > b->master_fd)
+ return +1;
+ return 0;
+}
+
+static int pty_find_by_fd(void *av, void *bv)
+{
+ int a = *(int *)av;
+ Pty b = (Pty)bv;
+
+ if (a < b->master_fd)
+ return -1;
+ else if (a > b->master_fd)
+ return +1;
+ return 0;
+}
+
+static tree234 *ptys_by_fd = NULL;
+
+/*
+ * We also have a tree sorted by child pid, so that when we wait()
+ * in response to the signal we know which backend instance is the
+ * owner of the process that caused the signal.
+ */
+static int pty_compare_by_pid(void *av, void *bv)
+{
+ Pty a = (Pty)av;
+ Pty b = (Pty)bv;