+static void pager_open(void) {
+ int fd[2];
+ const char *pager;
+
+ if (pager_pid > 0)
+ return;
+
+ if (!on_tty() || arg_no_pager)
+ return;
+
+ if ((pager = getenv("PAGER")))
+ if (!*pager || streq(pager, "cat"))
+ return;
+
+ /* Determine and cache number of columns before we spawn the
+ * pager so that we get the value from the actual tty */
+ columns();
+
+ if (pipe(fd) < 0) {
+ log_error("Failed to create pager pipe: %m");
+ return;
+ }
+
+ pager_pid = fork();
+ if (pager_pid < 0) {
+ log_error("Failed to fork pager: %m");
+ close_pipe(fd);
+ return;
+ }
+
+ /* In the child start the pager */
+ if (pager_pid == 0) {
+
+ dup2(fd[0], STDIN_FILENO);
+ close_pipe(fd);
+
+ setenv("LESS", "FRSX", 0);
+
+ prctl(PR_SET_PDEATHSIG, SIGTERM);
+
+ if (pager) {
+ execlp(pager, pager, NULL);
+ execl("/bin/sh", "sh", "-c", pager, NULL);
+ } else {
+ /* Debian's alternatives command for pagers is
+ * called 'pager'. Note that we do not call
+ * sensible-pagers here, since that is just a
+ * shell script that implements a logic that
+ * is similar to this one anyway, but is
+ * Debian-specific. */
+ execlp("pager", "pager", NULL);
+
+ execlp("less", "less", NULL);
+ execlp("more", "more", NULL);
+ }
+
+ log_error("Unable to execute pager: %m");
+ _exit(EXIT_FAILURE);
+ }
+
+ /* Return in the parent */
+ if (dup2(fd[1], STDOUT_FILENO) < 0)
+ log_error("Failed to duplicate pager pipe: %m");
+
+ close_pipe(fd);
+}
+
+static void pager_close(void) {
+ siginfo_t dummy;
+
+ if (pager_pid <= 0)
+ return;
+
+ /* Inform pager that we are done */
+ fclose(stdout);
+ wait_for_terminate(pager_pid, &dummy);
+ pager_pid = 0;
+}
+