Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define bfsize 100
- int main(int argc, char **argv)
- {
- shell();
- return 0;
- }
- void shell(void)
- {
- char *command;
- char **arguments;
- int status;
- do {
- printf("> ");
- command = readcommand();
- arguments = splitcommand(command);
- status = shellexecution(arguments);
- free(command);
- free(arguments);
- } while (status);
- }
- char *readcommand(void)
- {
- char *command = NULL;
- size_t buffersize = 0;
- getline(&command, &buffersize, stdin);
- return command;
- }
- char **splitcommand(char *command)
- {
- int buffersize = bfsize ;
- i = 0;
- char **tokens = malloc(buffersize * sizeof(char*));
- char *token;
- if (!tokens) {
- printf("An error occured \n");
- exit(1);
- }
- token = strtok(line, bfsize);
- while (token != NULL) {
- tokens[i] = token;
- i++;
- if (i >= buffersize) {
- buffersize = buffersize + bfsize;
- tokens = realloc(tokens, buffersize * sizeof(char*));
- if (!tokens) {
- printf("An error occured\n");
- exit(1);
- }
- }
- token = strtok(NULL, bfsize);
- }
- tokens[i] = NULL;
- return tokens;
- }
- int shellexecution(char **args)
- {
- pid_t pid;
- pid_t wpid;
- int status;
- pid = fork();
- if (pid == 0) {
- if (execvp(args[0], args) == -1) {
- printf("An error occured \n");
- }
- exit(1);
- } else if (pid < 0) {
- printf("An error occured \n");
- } else {
- do {
- wpid = waitpid(pid, &status, WUNTRACED);
- } while (!WIFEXITED(status) && !WIFSIGNALED(status));
- }
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement