// Make a shell which supports // exiting the shell with exit or Ctrl D // changing the current directory with cd // printing directory with getcwd // run the specificed program in the current dir using posix_spawn // should work for full path or relative path // simple args, separated by spaces #include #include #include #include #include #include #include #include #define BUFFER_SIZE 8192 extern char **environ; int main(void) { char buffer[BUFFER_SIZE]; while (1) { printf(":) "); if (fgets(buffer, BUFFER_SIZE, stdin) == NULL){ printf("\n"); break; } // Get rid of trailing newline character; size_t len_input = strlen(buffer); if (buffer[len_input - 1] == '\n' ){ buffer[len_input - 1] = '\0'; } if (strcmp(buffer,"exit") == 0) { break; } // cd XXXXXXXXXXXX if (strncmp(buffer, "cd ", 3) == 0) { chdir(buffer+3); } else if (strcmp(buffer, "pwd") == 0) { char path_buffer[PATH_MAX]; getcwd(path_buffer, PATH_MAX); printf("%s\n", path_buffer); } else { //ls -l asdf pid_t process_id; //"/bin/ls" char *args[128]; char *tokens = strtok(buffer, " "); int argc = 0; while (tokens != NULL && argc < 127) { args[argc++] = tokens; tokens = strtok(NULL, " "); } args[argc++]= NULL; int ret = posix_spawnp(&process_id, args[0], NULL, NULL, args, environ); if (ret != 0) { errno = ret; fprintf(stderr, "No %s\n", strerror(errno)); } else { waitpid(process_id, NULL, 0); } } } return 0; }