zoukankan      html  css  js  c++  java
  • C语言接口的写法(以toyls命令为例)

     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, " 	
    ");
    22     for (i++; argv[i - 1] != NULL; i++) {
    23         argv[i] = strtok(NULL, " 	
    ");
    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 }
    View Code
  • 相关阅读:
    OSPF协议 LSAs
    OSPF协议基础
    交换机Access Trunk Hybrid端口
    网络地址转换 NAT
    访问控制列表 ACL
    路由协议 RIP
    动态路由协议
    static 变量
    Unix网络编程 -- ubuntu下搭建编译环境( 解决unp.h 编译等问题)
    linux 错误处理
  • 原文地址:https://www.cnblogs.com/takeaction/p/4341883.html
Copyright © 2011-2022 走看看