~emersion/mrsh

ref: bda92abbcf206e6374593ee7e1962ba6341be98e mrsh/builtin/exit.c -rw-r--r-- 644 bytes View raw
bda92abbemersion Fix error handling in basic frontend 1 year, 8 months 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
#include <errno.h>
#include <mrsh/builtin.h>
#include <stdio.h>
#include <stdlib.h>
#include "builtin.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 EXIT_FAILURE;
	}

	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 EXIT_FAILURE;
		}
		status = (int)status_long;
	}

	state->exit = status;
	return EXIT_SUCCESS;
}