~emersion/mrsh

mrsh/builtin/exit.c -rw-r--r-- 784 bytes View raw
7105405aBenjamin Lowry Makefile: remove getopt.h from public_includes a day ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <errno.h>
#include <mrsh/builtin.h>
#include <stdio.h>
#include <stdlib.h>
#include "builtin.h"
#include "shell/task.h"

static const char exit_usage[] = "usage: exit [n]\n";

int builtin_exit(struct mrsh_state *state, int argc, char *argv[]) {
	if (argc > 2) {
		fprintf(stderr, exit_usage);
		return 1;
	}

	int status = 0;
	if (argc > 1) {
		char *endptr;
		errno = 0;
		long status_long = strtol(argv[1], &endptr, 10);
		if (endptr[0] != '\0' || errno != 0 ||
				status_long < 0 || status_long > 255) {
			fprintf(stderr, exit_usage);
			return 1;
		}
		status = (int)status_long;
	}

	struct mrsh_call_frame_priv *frame_priv = call_frame_get_priv(state->frame);

	state->exit = status;
	frame_priv->branch_control = MRSH_BRANCH_EXIT;
	return TASK_STATUS_INTERRUPTED;
}