Newer
Older
antarktida-shell / src / main.c
@Master-Lamasster Master-Lamasster on 30 Sep 1 KB Initial commit
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "config.h"
#include "ANTbin.h"

char *usr_name = "PIN";

char **parse_line(char *line) {
    char **args = malloc(MAX_ARGS * sizeof(char *));

    if (args == NULL) {
        perror("ant_sh: malloc failed");
        return NULL;
    }

    int i = 0;
    char *token = strtok(line, " \t\n");
    while (token != NULL && i < MAX_ARGS - 1) {
        args[i++] = token;
        token = strtok(NULL, " \t\n");
    }
    args[i] = NULL;
    return args;
}

int main(void) {
    char prompt[128];

    snprintf(prompt, sizeof(prompt), "\033[1;36m%s@ant_sh -> \033[0m", usr_name);

    while (1) {

        char *line = readline(prompt);

        if (line == NULL) {
            fprintf(stderr, "\033[1;36m\nDosvidanie...\033[0m\n");
            break;
        }

        if (*line == '\0') {
            free(line);
            continue;
        }

        add_history(line);

        char **args = parse_line(line);
        if (args == NULL || args[0] == NULL) {
            if (args) free(args);
            continue;
        }

        if (strcmp(args[0], "sys") == 0) {
            if (args[1]) system(args[1]);
            free(args);
            free(line);
            continue;
        }

        ANTbin_fn fn = ANTbin_find(args[0]);
        if (fn) {
            fn(args);
            free(args);
            free(line);
            continue;
        }

        if (strcmp(args[0], "exit") == 0) {
            fprintf(stderr, "\033[1;36mDosvidanie...\033[0m\n");
            free(args);
            free(line);
            break;
        }

        pid_t pid = fork();
        if (pid == 0) {
            execvp(args[0], args);
            perror("ant_sh");
            _exit(127);
        } else if (pid > 0) {
            int status;
            waitpid(pid, &status, 0);
        }

        free(args);
        free(line);
    }

    return 0;
}