~emersion/mrsh

9371d6094e78645f0ec0c85b6cd5b6c8ec9638fc — Drew DeVault 3 years ago beacca6
Implement times, : builtins
5 files changed, 55 insertions(+), 0 deletions(-)

M builtin/builtin.c
A builtin/colon.c
A builtin/times.c
M include/builtin.h
M meson.build
M builtin/builtin.c => builtin/builtin.c +2 -0
@@ 12,7 12,9 @@ struct builtin_map {

static struct builtin_map builtins[] = {
	// Keep alpha sorted
	{ ":", builtin_colon },
	{ "exit", builtin_exit },
	{ "times", builtin_times },
};

static int builtin_compare(const void *_a, const void *_b) {

A builtin/colon.c => builtin/colon.c +8 -0
@@ 0,0 1,8 @@
#include <mrsh/builtin.h>
#include <stdlib.h>
#include "builtin.h"

int builtin_colon(struct mrsh_state *state, int argc, char *argv[]) {
	/* thils builtin does not do anything */
	return EXIT_SUCCESS;
}

A builtin/times.c => builtin/times.c +41 -0
@@ 0,0 1,41 @@
#include <errno.h>
#include <mrsh/builtin.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/times.h>
#include <unistd.h>
#include "builtin.h"

static const char times_usage[] = "usage: times\n";

int builtin_times(struct mrsh_state *state, int argc, char *argv[]) {
	if (argc > 1) {
		fprintf(stderr, times_usage);
		return EXIT_FAILURE;
	}

	struct tms buf;
	long clk_tck = sysconf(_SC_CLK_TCK);
	if (clk_tck == -1) {
		fprintf(stderr, "sysconf error: %s", strerror(errno));
		return EXIT_FAILURE;
	}

	if (times(&buf) == -1) {
		fprintf(stderr, "times error: %s", strerror(errno));
		return EXIT_FAILURE;
	}

	printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
			(int)(buf.tms_utime / clk_tck / 60),
			((double) buf.tms_utime) / clk_tck,
			(int)(buf.tms_stime / clk_tck / 60),
			((double) buf.tms_stime) / clk_tck,
			(int)(buf.tms_cutime / clk_tck / 60),
			((double) buf.tms_cutime) / clk_tck,
			(int)(buf.tms_cstime / clk_tck / 60),
			((double)buf.tms_cstime) / clk_tck);

	return EXIT_SUCCESS;
}

M include/builtin.h => include/builtin.h +2 -0
@@ 4,6 4,8 @@
typedef int (*mrsh_builtin_func_t)(struct mrsh_state *state,
	int argc, char *argv[]);

int builtin_colon(struct mrsh_state *state, int argc, char *argv[]);
int builtin_exit(struct mrsh_state *state, int argc, char *argv[]);
int builtin_times(struct mrsh_state *state, int argc, char *argv[]);

#endif

M meson.build => meson.build +2 -0
@@ 24,7 24,9 @@ executable(
		'ast.c',
		'buffer.c',
		'builtin/builtin.c',
		'builtin/colon.c',
		'builtin/exit.c',
		'builtin/times.c',
		'main.c',
		'parser.c',
		'shell/process.c',