2 * logsave.c --- A program which saves the output of a program until
5 * Copyright (C) 2003 Theodore Ts'o.
8 * This file may be redistributed under the terms of the GNU Public
13 #define _XOPEN_SOURCE 600 /* for inclusion of sa_handler in Solaris */
19 #include <sys/types.h>
42 static void usage(char *progname)
44 printf("Usage: %s [-v] [-d dir] logfile program\n", progname);
49 #define SEND_CONSOLE 0x02
50 #define SEND_BOTH 0x03
52 static void send_output(const char *buffer, int c, int flag)
59 if (flag & SEND_CONSOLE)
61 if (!(flag & SEND_LOG))
64 write(outfd, buffer, c);
66 n = realloc(outbuf, outbufsize + c);
69 memcpy(((char *)outbuf)+outbufsize, buffer, c);
75 static int do_read(int fd)
78 char buffer[4096], *cp, *sep;
80 c = read(fd, buffer, sizeof(buffer)-1);
84 send_output(buffer, c, SEND_CONSOLE);
89 cp = strchr(cp, '\002');
96 sep = strchr(cp, '\001');
99 send_output(cp, 0, SEND_LOG);
107 send_output(buffer, c, SEND_BOTH);
111 static void signal_term(int sig)
114 kill(child_pid, sig);
117 static int run_program(char **argv)
132 memset(&sa, 0, sizeof(struct sigaction));
133 sa.sa_handler = signal_term;
134 sigaction(SIGINT, &sa, 0);
135 sigaction(SIGTERM, &sa, 0);
137 sa.sa_flags = SA_RESTART;
147 dup2(fds[1],1); /* fds[1] replaces stdout */
148 dup2(fds[1],2); /* fds[1] replaces stderr */
149 close(fds[0]); /* don't need this here */
151 execvp(argv[0], argv);
158 while (!(waitpid(pid, &status, WNOHANG ))) {
165 if ( WIFEXITED(status) ) {
166 rc = WEXITSTATUS(status);
168 send_output(argv[0], 0, SEND_BOTH);
169 sprintf(buffer, " died with exit status %d\n", rc);
170 send_output(buffer, 0, SEND_BOTH);
173 if (WIFSIGNALED(status)) {
174 send_output(argv[0], 0, SEND_BOTH);
175 sprintf(buffer, "died with signal %d\n",
177 send_output(buffer, 0, SEND_BOTH);
185 static int copy_from_stdin(void)
192 ((c < 0) && ((errno == EAGAIN) || (errno == EINTR)))) {
208 int main(int argc, char **argv)
212 int openflags = O_CREAT|O_WRONLY|O_TRUNC;
213 int send_flag = SEND_LOG;
217 while ((c = getopt(argc, argv, "+asv")) != EOF) {
220 openflags &= ~O_TRUNC;
221 openflags |= O_APPEND;
228 send_flag |= SEND_CONSOLE;
232 if (optind == argc || optind+1 == argc)
234 outfn = argv[optind];
239 outfd = open(outfn, openflags, 0644);
240 do_stdin = !strcmp(argv[0], "-");
242 send_output("Log of ", 0, send_flag);
244 send_output("stdin", 0, send_flag);
246 for (cpp = argv; *cpp; cpp++) {
247 send_output(*cpp, 0, send_flag);
248 send_output(" ", 0, send_flag);
251 send_output("\n", 0, send_flag);
253 send_output(ctime(&t), 0, send_flag);
254 send_output("\n", 0, send_flag);
257 rc = copy_from_stdin();
259 rc = run_program(argv);
261 send_output("\n", 0, send_flag);
263 send_output(ctime(&t), 0, send_flag);
264 send_output("----------------\n", 0, send_flag);
274 printf("Backgrounding to save %s later\n",
278 setsid(); /* To avoid getting killed by init */
280 outfd = open(outfn, openflags, 0644);
283 write(outfd, outbuf, outbufsize);