Allow execution of external commands

This commit is contained in:
Artur Tamborski 2018-12-23 02:29:01 +01:00
parent acd001edbb
commit e1d4fa88ac

View File

@ -5,6 +5,9 @@
#include <signal.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "icmd.h"
@ -20,6 +23,19 @@ char *g_tokens[TOKENS_NUM_MAX];
char g_args[TOKENS_ARGS_SIZE];
void
print(char *format, ...)
{
va_list args;
va_start(args, format);
printf("psh: ");
vprintf(format, args);
putchar('\n');
va_end(args);
}
void
die(int status, char *format, ...)
{
@ -27,15 +43,18 @@ die(int status, char *format, ...)
va_start(args, format);
if (status != 0)
puts("Error: ");
puts("psh: error: ");
vprintf(format, args);
if (status != 0)
puts("! Exiting...");
puts("! exiting...");
putchar('\n');
if (status < 0)
perror("Reason");
exit(status);
perror("reason");
va_end(args);
exit(status);
}
@ -79,6 +98,32 @@ tokenize(char *input)
return argc;
}
int
call_ecmd(int argc, char **argv)
{
int status;
char *err;
pid_t pid;
pid = fork();
if (pid == -1)
die(-1, "fork failed");
/* parent */
if (pid)
return wait(&status), status;
/* child */
execvp(argv[0], argv);
/* if we are here then called program failed */
err = strerror(errno);
print("%s: %s", argv[0], err);
return -1;
}
int
main(int argc, char **argv)
@ -94,7 +139,7 @@ main(int argc, char **argv)
for (;;)
{
if (getcwd(cwd, sizeof(cwd)) == NULL)
die(-1, "Could not get current directory");
die(1, "Could not get current directory");
printf("[%s] ", cwd);
@ -102,12 +147,25 @@ main(int argc, char **argv)
die(0, "Caught ^D");
if ((num_tokens = tokenize(input)) < 0)
die(1, "Could not parse tokens");
die(1, "Could not parse input");
/* no input, start again */
if (num_tokens == 0)
continue;
if ((ret = call_icmd(num_tokens, g_tokens) < 0))
puts("Internal command failed!");
/* search for internal commands first */
if ((ret = find_icmd(g_tokens[0])) >= 0)
{
ret = call_icmd(ret, num_tokens, g_tokens);
if (ret)
print("Internal command '%s' failed with error code: %d", g_tokens[0], ret);
continue;
}
ret = call_ecmd(num_tokens, g_tokens);
if (ret)
print("External command '%s' failed with error code: %d", g_tokens[0], ret);
}
}