mkstemp implementation: Specify a umask for open().
[git/mingw.git] / pager.c
blob48b3cb3c17b5a50de289085ea8fbbb8567502854
1 #include "cache.h"
2 #include "spawn-pipe.h"
4 #include <sys/select.h>
6 /*
7 * This is split up from the rest of git so that we might do
8 * something different on Windows, for example.
9 */
11 #ifndef __MINGW32__
12 static void run_pager(const char *pager)
15 * Work around bug in "less" by not starting it until we
16 * have real input
18 fd_set in;
20 FD_ZERO(&in);
21 FD_SET(0, &in);
22 select(1, &in, NULL, &in, NULL);
24 execlp(pager, pager, NULL);
25 execl("/bin/sh", "sh", "-c", pager, NULL);
27 #else
28 static pid_t pager_pid;
29 static void collect_pager(void)
31 close(1); /* signals EOF to pager */
32 cwait(NULL, pager_pid, 0);
34 #endif
36 void setup_pager(void)
38 #ifndef __MINGW32__
39 pid_t pid;
40 #else
41 const char *pager_argv[] = { "sh", "-c", NULL, NULL };
42 #endif
43 int fd[2];
44 const char *pager = getenv("GIT_PAGER");
46 if (!isatty(1))
47 return;
48 if (!pager)
49 pager = getenv("PAGER");
50 if (!pager)
51 pager = "less";
52 else if (!*pager || !strcmp(pager, "cat"))
53 return;
55 pager_in_use = 1; /* means we are emitting to terminal */
57 if (pipe(fd) < 0)
58 return;
59 #ifndef __MINGW32__
60 pid = fork();
61 if (pid < 0) {
62 close(fd[0]);
63 close(fd[1]);
64 return;
67 /* return in the child */
68 if (!pid) {
69 dup2(fd[1], 1);
70 close(fd[0]);
71 close(fd[1]);
72 return;
75 /* The original process turns into the PAGER */
76 dup2(fd[0], 0);
77 close(fd[0]);
78 close(fd[1]);
80 setenv("LESS", "FRSX", 0);
81 run_pager(pager);
82 die("unable to execute pager '%s'", pager);
83 exit(255);
84 #else
85 /* spawn the pager */
86 pager_argv[2] = pager;
87 pager_pid = spawnvpe_pipe(pager_argv[0], pager_argv, environ, fd, NULL);
88 if (pager_pid < 0)
89 return;
91 /* original process continues, but writes to the pipe */
92 dup2(fd[1], 1);
93 close(fd[1]);
95 /* this makes sure that the parent terminates after the pager */
96 atexit(collect_pager);
97 #endif