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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h>
#define ZERO '\0'
#define SIZE 512
#define NUM 32
#define SEP " "
const char* GetUserName() { const char* name = getenv("USER"); if (name == NULL) { return "None"; } return name; }
const char* GetHostName() { static char hostname[256]; if (gethostname(hostname, sizeof(hostname)) == 0) { return hostname; } return "None"; }
const char* GetCwd() { const char* cwd = getenv("PWD"); if (cwd == NULL) { return "None"; } return cwd; }
void MakeCommandLine() { char commandline[SIZE];
const char* username = GetUserName(); const char* hostname = GetHostName(); const char* cwd = GetCwd();
snprintf(commandline, sizeof(commandline), "[%s@%s %s]> ", username, hostname, cwd); printf("%s", commandline); fflush(stdout); }
int GetUserCommand(char usercommand[], size_t n) { char *s = fgets(usercommand, n, stdin); if (s == NULL) { return -1; } usercommand[strlen(usercommand) - 1] = ZERO; return strlen(usercommand); }
char *gArgv[NUM];
void SplitCommand(char command[], size_t n){ gArgv[0] = strtok(command, SEP); int index = 1; while (gArgv[index++] = strtok(NULL, SEP)); }
void ExecuteCommand() { pid_t id = fork();
if (id < 0) { exit(1); } else if (id == 0) { execvp(gArgv[0], gArgv); exit(errno); } else { int status = 0; pid_t rid = waitpid(id, &status, 0); } }
int main() {
while (1) { MakeCommandLine();
char usercommand[SIZE]; int n = GetUserCommand(usercommand, sizeof(usercommand));
SplitCommand(usercommand, sizeof(usercommand));
ExecuteCommand(); }
return 0; }
|