#include #include #include #include #include #include #include #include #include void handle_int() { /* handle ctrl-c */ printf("\n"); rl_on_new_line(); rl_replace_line("", 0); rl_redisplay(); /* thanks James Taylor on Stack Overflow */ } void usage(char **argv) { fprintf(stderr, "usage: %s [-a] command\n", argv[0]); exit(1); } int main(int argc, char *argv[]) { bool append = false; if (argc < 2 || argc > 3) usage(argv); if (argc > 1 && argv[1][0] == '-') { if (argv[1][1] != 'a' || argc < 3) usage(argv); append = true; } int size = strlen(argv[argc-1]) + 3 + 1; char *prompt = malloc(size); if (prompt == NULL) err(1, NULL); snprintf(prompt, size, "%s& ", argv[argc-1]); struct sigaction act = {0}; act.sa_handler = handle_int; sigaction(SIGINT, &act, NULL); rl_clear_signals(); /* tell readline to ignore signals */ while (true) { char *input = readline(prompt); if (input == NULL) /* ctrl-d */ break; if (input[0] != '\0') add_history(input); int size = strlen(argv[argc-1]) + 1 + strlen(input) + 1; char *command = malloc(size); if (command == NULL) err(1, NULL); if (strncmp(input, "!cd ", 4) == 0) { if (chdir(input + 4) == -1) warn(NULL); goto next; } if (input[0] == '!') snprintf(command, size, "%s", input + 1); else if (append) snprintf(command, size, "%s %s", input, argv[argc-1]); else snprintf(command, size, "%s %s", argv[argc-1], input); system(command); next: free(input); free(command); } free(prompt); return 0; }