[PATCH 2/2] time: implement -a and -o

Tommi Rantala tt.rantala at gmail.com
Mon Apr 24 16:08:54 UTC 2017


From: Tommi Rantala <tommi.t.rantala at nokia.com>

Add support for -a and -o options, similar to GNU time.

Signed-off-by: Tommi Rantala <tommi.t.rantala at nokia.com>
---
 miscutils/time.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)

diff --git a/miscutils/time.c b/miscutils/time.c
index 7c457a9..5437731 100644
--- a/miscutils/time.c
+++ b/miscutils/time.c
@@ -21,11 +21,13 @@
 //kbuild:lib-$(CONFIG_TIME) += time.o
 
 //usage:#define time_trivial_usage
-//usage:       "[-vp] PROG ARGS"
+//usage:       "[-vpa] [-o FILE] PROG ARGS"
 //usage:#define time_full_usage "\n\n"
 //usage:       "Run PROG, display resource usage when it exits\n"
 //usage:     "\n	-v	Verbose"
 //usage:     "\n	-p	POSIX output format"
+//usage:     "\n	-a	Append to the file specified with -o"
+//usage:     "\n	-o FILE	Write result to FILE instead of stderr"
 
 #include "libbb.h"
 #include <sys/resource.h> /* getrusage */
@@ -414,21 +416,30 @@ int time_main(int argc UNUSED_PARAM, char **argv)
 {
 	resource_t res;
 	const char *output_format = default_format;
+	char *output_filename = NULL;
+	int output_fd = STDERR_FILENO;
 	int opt;
 
 	opt_complementary = "-1"; /* at least one arg */
 	/* "+": stop on first non-option */
-	opt = getopt32(argv, "+vp");
+	opt = getopt32(argv, "+vpao:", &output_filename);
 	argv += optind;
 	if (opt & 1)
 		output_format = long_format;
 	if (opt & 2)
 		output_format = posix_format;
+	if (opt & 8) {
+		int append = opt & 4;
+		/* O_CLOEXEC: do not inherit the fd to the child process. */
+		int flags = O_CREAT | O_WRONLY | O_CLOEXEC |
+			(append ? O_APPEND : O_TRUNC);
+		output_fd = xopen(output_filename, flags);
+	}
 
 	run_command(argv, &res);
 
 	/* Cheat. printf's are shorter :) */
-	xdup2(STDERR_FILENO, STDOUT_FILENO);
+	xdup2(output_fd, STDOUT_FILENO);
 	summarize(output_format, argv, &res);
 
 	if (WIFSTOPPED(res.waitstatus))
-- 
2.9.3



More information about the busybox mailing list