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
17 #include <sys/types.h>
36 static void usage(char *progname)
38 printf("Usage: %s [-v] [-d dir] logfile program\n", progname);
43 #define SEND_CONSOLE 0x02
44 #define SEND_BOTH 0x03
46 static void send_output(const char *buffer, int c, int flag)
53 if (flag & SEND_CONSOLE)
55 if (!(flag & SEND_LOG))
58 write(outfd, buffer, c);
60 n = realloc(outbuf, outbufsize + c);
63 memcpy(((char *)outbuf)+outbufsize, buffer, c);
69 static int do_read(int fd)
72 char buffer[4096], *cp, *sep;
74 c = read(fd, buffer, sizeof(buffer)-1);
78 send_output(buffer, c, SEND_CONSOLE);
83 cp = strchr(cp, '\002');
90 sep = strchr(cp, '\001');
93 send_output(cp, 0, SEND_LOG);
101 send_output(buffer, c, SEND_BOTH);
105 static int run_program(char **argv)
122 dup2(fds[1],1); /* fds[1] replaces stdout */
123 dup2(fds[1],2); /* fds[1] replaces stderr */
124 close(fds[0]); /* don't need this here */
126 execvp(argv[0], argv);
132 while (!(waitpid(pid, &status, WNOHANG ))) {
138 if ( WIFEXITED(status) ) {
139 rc = WEXITSTATUS(status);
141 send_output(argv[0], 0, SEND_BOTH);
142 sprintf(buffer, " died with exit status %d\n", rc);
143 send_output(buffer, 0, SEND_BOTH);
146 if (WIFSIGNALED(status)) {
147 send_output(argv[0], 0, SEND_BOTH);
148 sprintf(buffer, "died with signal %d\n",
150 send_output(buffer, 0, SEND_BOTH);
158 static int copy_from_stdin(void)
165 ((c < 0) && ((errno == EAGAIN) || (errno == EINTR)))) {
181 int main(int argc, char **argv)
185 int openflags = O_CREAT|O_WRONLY|O_TRUNC;
186 int send_flag = SEND_LOG;
190 while ((c = getopt(argc, argv, "+asv")) != EOF) {
193 openflags &= ~O_TRUNC;
194 openflags |= O_APPEND;
201 send_flag |= SEND_CONSOLE;
205 if (optind == argc || optind+1 == argc)
207 outfn = argv[optind];
212 outfd = open(outfn, openflags, 0644);
213 do_stdin = !strcmp(argv[0], "-");
215 send_output("Log of ", 0, send_flag);
217 send_output("stdin", 0, send_flag);
219 for (cpp = argv; *cpp; cpp++) {
220 send_output(*cpp, 0, send_flag);
221 send_output(" ", 0, send_flag);
224 send_output("\n", 0, send_flag);
226 send_output(ctime(&t), 0, send_flag);
227 send_output("\n", 0, send_flag);
230 rc = copy_from_stdin();
232 rc = run_program(argv);
234 send_output("\n", 0, send_flag);
236 send_output(ctime(&t), 0, send_flag);
237 send_output("----------------\n", 0, send_flag);
247 printf("Backgrounding to save %s later\n",
251 setsid(); /* To avoid getting killed by init */
253 outfd = open(outfn, openflags, 0644);
256 write(outfd, outbuf, outbufsize);