1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
#include <err.h>
#include <readline/history.h>
#include <readline/readline.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
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;
}
|