Do not leak pipe file handles into the child processes.
[git/mingw.git] / pager.c
blobb2a37e26588e9f063b6a57e3fb680e964a14f9e5
1 #include "cache.h"
2 #include "spawn-pipe.h"
4 /*
5 * This is split up from the rest of git so that we might do
6 * something different on Windows, for example.
7 */
9 #ifndef __MINGW32__
10 static void run_pager(const char *pager)
12 execlp(pager, pager, NULL);
13 execl("/bin/sh", "sh", "-c", pager, NULL);
15 #endif
17 void setup_pager(void)
19 #ifndef __MINGW32__
20 pid_t pid;
21 #else
22 const char *pager_argv[] = { "sh", "-c", NULL, NULL };
23 #endif
24 int fd[2];
25 const char *pager = getenv("GIT_PAGER");
27 if (!isatty(1))
28 return;
29 if (!pager)
30 pager = getenv("PAGER");
31 if (!pager)
32 pager = "less";
33 else if (!*pager || !strcmp(pager, "cat"))
34 return;
36 pager_in_use = 1; /* means we are emitting to terminal */
38 if (pipe(fd) < 0)
39 return;
40 #ifndef __MINGW32__
41 pid = fork();
42 if (pid < 0) {
43 close(fd[0]);
44 close(fd[1]);
45 return;
48 /* return in the child */
49 if (!pid) {
50 dup2(fd[1], 1);
51 close(fd[0]);
52 close(fd[1]);
53 return;
56 /* The original process turns into the PAGER */
57 dup2(fd[0], 0);
58 close(fd[0]);
59 close(fd[1]);
61 setenv("LESS", "FRSX", 0);
62 run_pager(pager);
63 die("unable to execute pager '%s'", pager);
64 exit(255);
65 #else
66 /* spawn the pager */
67 pager_argv[2] = pager;
68 if (spawnvpe_pipe(pager_argv[0], pager_argv, environ, fd, NULL) < 0)
69 return;
71 /* original process continues, but writes to the pipe */
72 dup2(fd[1], 1);
73 close(fd[1]);
74 #endif