I make a simple shell. It should also be able to read text files line by line. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
void my_exit() {
printf("Bye!\n");
exit(0);
}
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
char buff[1024];
int fid;
char dir[50];
getcwd(dir,50);
char *user = getenv("USER");
char *host = getenv("HOST");
printf("%s@%s:%s> ", user, host, dir);
while (fgets(buff, 1024, stdin) != NULL) {
int i = strlen(buff) - 1;
if (buff[i] == '\n') {
buff[i] = 0;
}
if (!strcmp(buff,"exit")) {
my_exit();
}
fid = fork();
if (fid == 0) {
int nargs = 0;
for (int i = 0; buff[i] != '\0'; i++) {
if (buff[i] == ' ') nargs ++;
}
char **args = malloc((sizeof(char*)*(nargs + 2)));
args[nargs+1] = NULL;
char *temp = strtok (buff," ");
for (int i = 0; temp != NULL; i++) {
args[i] = malloc (strlen(temp) + 1);
strcpy(args[i], temp);
temp = strtok (NULL, " ");
}
if (execvp(args[0], args)) {
my_exit();
}
}
else {
wait(NULL);
}
printf("%s@%s:%s> ", user, host, dir);
}
my_exit();
return 0;
}
When I run it as a shell, it works fine. When i'm running. / myshell <command.txt, it does not work.
commands.txt:
ls -l -a
pwd
ls
But the way out:
>Bye!
>Bye!
>Bye!
>Bye!
>Bye!
>Bye!>Bye!
>Bye!
>Bye!
>Bye!
Doesn't even follow my commands. Any ideas? I thought my while loop is pretty simple.
source
share