psh/src/main.c
2018-12-17 01:47:01 +01:00

125 lines
2.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <signal.h>
#include <string.h>
#include <limits.h>
#include "icmd.h"
#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
tokenize(char *input)
{
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 input[INPUT_MAX_LEN];
char cwd[PATH_MAX_LEN];
int num_tokens, ret;
signal(SIGINT, sigint);
signal(SIGHUP, sighup);
signal(SIGQUIT, sighup);
for (;;)
{
if (getcwd(cwd, sizeof(cwd)) == NULL)
die(-1, "Could not get current directory");
printf("[%s] ", cwd);
if (!fgets(input, sizeof(input)-1, stdin))
die(0, "Caught ^D");
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!");
}
}