Add basic token support for command args, clean up

This commit is contained in:
Artur Tamborski 2018-12-17 01:47:01 +01:00
parent d74c3512a4
commit 858eb84444

View File

@ -1,49 +1,124 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <signal.h>
#include <string.h>
#include <limits.h>
#include "icmd.h"
/* should be enough */
#define CMD_LINE_MAX 1024
#define CMD_PATH_MAX 4096
#define INPUT_MAX_LEN 1024
#define PATH_MAX_LEN 4096
#define TOKENS_NUM_MAX 512
#define TOKENS_ARGS_SIZE 2048
char *g_tokens[TOKENS_NUM_MAX];
char g_args[TOKENS_ARGS_SIZE];
void
die(int status, char *format, ...)
{
va_list args;
va_start(args, format);
if (status != 0)
puts("Error: ");
vprintf(format, args);
if (status != 0)
puts("! Exiting...");
putchar('\n');
if (status < 0)
perror("Reason");
exit(status);
va_end(args);
}
void
sighup(int signal)
{
die(1, "Parent process has ben killed");
}
void
sigint(int signal)
{
die(0, "Caught ^C");
}
int
die(char *s)
tokenize(char *input)
{
perror(s);
exit(-1);
char curr, prev = '\n';
char **tokens = g_tokens;
char *start = g_args;
char *args = g_args;
int real_input = 0;
int argc = 0;
while ((curr = *input++) != '\0')
{
if (curr == ' ' || curr == '\n')
{
if (curr == prev || !real_input)
continue;
*tokens++ = start;
*args++ = '\0';
start = args;
argc++;
if (curr == '\n')
break;
} else
{
*args++ = curr;
real_input = 1;
}
prev = curr;
}
tokens = NULL;
return argc;
}
int
main(int argc, char **argv)
{
char line[CMD_LINE_MAX];
char cwd[CMD_PATH_MAX];
char *pline = line;
int ret;
char input[INPUT_MAX_LEN];
char cwd[PATH_MAX_LEN];
int num_tokens, ret;
signal(SIGINT, sigint);
signal(SIGHUP, sighup);
signal(SIGQUIT, sighup);
for (;;)
{
/* todo: does it really fail? */
if (getcwd(cwd, sizeof(cwd)) == NULL)
die("getcwd()");
die(-1, "Could not get current directory");
printf("[%s] ", cwd);
fgets(line, sizeof(line), stdin);
ret = call_icmds(line);
if (ret == INT_MAX)
puts("no such internal command, going on...");
else if (ret == 0)
puts("internal command succeded!");
else
puts("internal command succeded!");
}
if (!fgets(input, sizeof(input)-1, stdin))
die(0, "Caught ^D");
return 0;
if ((num_tokens = tokenize(input)) < 0)
die(1, "Could not parse tokens");
if (num_tokens == 0)
continue;
if ((ret = call_icmd(num_tokens, g_tokens) < 0))
puts("Internal command failed!");
}
}