C语言接口的写法(以toyls命令为例)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <unistd.h> 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 #define CMDSIZE 4096 8 9 static void prompt(void) 10 { 11 printf("[mysh]$ "); 12 fflush(stdout); 13 } 14 15 static void getcmd(char *cmd, char **argv) 16 { 17 int i = 0; 18 19 fgets(cmd, CMDSIZE, stdin); 20 21 argv[i] = strtok(cmd, " \t\n"); 22 for (i++; argv[i - 1] != NULL; i++) { 23 argv[i] = strtok(NULL, " \t\n"); 24 } 25 } 26 27 static void myexit(char **argv) 28 { 29 exit(0); 30 } 31 32 static void mycd(char **argv) 33 { 34 chdir(argv[1]); 35 } 36 37 #define NAMESIZE 256 38 struct { 39 void (*func)(char **); 40 char name[NAMESIZE]; 41 } internal_list[] = { 42 {myexit, "exit"}, 43 {mycd, "cd"}, 44 {NULL, }, 45 }; 46 47 static int internal_ind(const char *name) 48 { 49 int i; 50 51 for (i = 0; internal_list[i].func != NULL; i++) { 52 if (strcmp(name, internal_list[i].name) == 0) { 53 return i; 54 } 55 } 56 return -1; 57 } 58 59 int main(void) 60 { 61 char cmd[CMDSIZE]; 62 char *argv[CMDSIZE / 2]; 63 pid_t pid; 64 int ind; 65 66 while (1) { 67 prompt(); 68 69 getcmd(cmd, argv); 70 if ((ind = internal_ind(argv[0])) != -1) { 71 internal_list[ind].func(argv); 72 } else { 73 pid = fork(); 74 /* if error */ 75 if (pid == 0) { 76 execvp(argv[0], argv); 77 perror(argv[0]); 78 exit(1); 79 } 80 wait(NULL); 81 } 82 } 83 84 return 0; 85 }