Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <string.h>
- typedef struct {
- char *prog;
- char **args;
- } command;
- command parseInput(char* input);
- int main(int argc, char *argv[])
- {
- while (1) {
- char input[512]; //store input line
- printf("$sshell "); //shell prompt
- fgets(input, 512, stdin); //read line into string
- input[strlen(input) - 1] = '\0';
- //check for exit command
- if (strcmp(input, "exit") == 0) {
- exit(0);
- } else {
- //create new process
- pid_t PID = fork();
- //if child process
- if (PID == 0) {
- int status;
- command comm = parseInput(input);
- status = execvp(comm.prog, comm.args);
- //if exec fails
- if (status != 0) {
- fprintf(stderr, "Error: command not found.\n");
- exit(42);
- //else exit the process
- } else {
- exit(0);
- }
- } else {
- int status;
- wait(&status);
- fprintf(stderr, "+ completed '%s' [%d]\n", input, WEXITSTATUS(status));
- }
- }
- }
- return EXIT_SUCCESS;
- }
- command parseInput(char *input) {
- command comm;
- int i = 1;
- char *token;
- token = strtok(input, " ");
- //printf("Got a token: %s\n", token);
- comm.prog = (char*) malloc(strlen(token) + 1);
- strcpy(comm.prog, token);
- comm.args = (char**) malloc(sizeof(char*) * 50);
- comm.args[0] = (char*) malloc(strlen(token) + 1);
- strcpy(comm.args[0], token);
- while(1) {
- token = strtok(NULL, " \n");
- if (token == NULL) {
- break;
- }
- comm.args[i] = (char*) malloc(strlen(token) + 1);
- strcpy(comm.args[i], token);
- }
- comm.args[i + 1] = (char*) malloc(sizeof((char*) NULL));
- comm.args[i + 1] = (char*) NULL;
- return comm;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement