summaryrefslogtreecommitdiff
path: root/src/cmd/jsh/jsh.c
blob: 320a93d6f8ad1b8afd36e39818ffa390c47d8e00 (plain)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include <ctype.h>

size_t getargs(const size_t n, char *args[n], FILE * const stream);
int shellexec(size_t n, char * const args[n]);

static bool run = true;

int main(int argc, char *argv[]) {
	char *words[BUFSIZ] = {NULL};
	FILE *fp = stdin;
	size_t numberofwords = 0;
	if (argc == 2) {
		if ((fp = fopen(argv[1], "r")) == NULL) {
			perror("jsh");
			return EXIT_FAILURE;
		}
	}
	while (run) {
		printf("$ ");
		numberofwords = getargs(BUFSIZ, words, fp);
		shellexec(BUFSIZ, words);
		for (int i = 0; i < numberofwords; i++) {
			free(words[i]);
			words[i] = NULL;
		}
	}
	return 0;
}

size_t getargs(const size_t n, char *args[n], FILE * const stream) {
	size_t i = 0;
	char c = 0, s[BUFSIZ], *sp = s;
	memset(s, '\0', sizeof(s));
	while ((c = fgetc(stream)) != EOF && i < n && sp < s + BUFSIZ) {
		if (isspace(c)) {
			*sp = '\0';
			args[i++] = strdup(s);
			sp = s;
			if (strcmp(args[i-1], "") == 0) {
				free(args[i-1]);
				args[i-1] = NULL;
				i--;
			}
			if (c == '\n') {
				break;
			}
		} else {
			*sp++ = c;
		}
	}
	return i;
}

int shellexec(size_t n, char * const args[n]) {
	if (strcmp(args[0], "exit") == 0) {
		run = false;
		return 0;
	}
	pid_t pid = fork();
	int status;
	if (pid == 0) {
		if (execvp(args[0], args) == -1) {
			perror("jsh");
		}
		exit(EXIT_FAILURE);
	} else if (pid < 0) {
		perror("jsh");
		exit(EXIT_FAILURE);
	} else {
		do {
		  waitpid(pid, &status, WUNTRACED);
		} while (!WIFEXITED(status) && !WIFSIGNALED(status));
	}
	return 0;
}