implement sample shell

  • sample shell
/*************************************************************************
  > File Name: shell.c
  > Author:perrynzhou 
  > Mail:[email protected] 
  > Created Time: Thu 20 Jun 2019 09:15:59 PM CST
 ************************************************************************/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
static const char *delimiter = " \t\n";
typedef struct
{
  glob_t gt;
  int (*cmd_cd_fn)(char **argv);
  int (*cmd_exit_fn)(char **argv);
  int (*cmd_help_fn)(char **argv);
} cmd_t;
static void prompt()
{
  fprintf(stdout, "zsh-0.1$ ");
}
void parsed_cmd(char *line, cmd_t *cmd)
{
  char *token;
  int flag = 0;
  while (1)
  {
    token = strsep(&line, delimiter);
    if (token == NULL)
    {
      break;
    }
    if (*token == '\0')
    {
      continue;
    }
    glob(token, GLOB_NOCHECK | GLOB_APPEND * flag, NULL, &cmd->gt);
    flag = 1;
  }
}
int main(int argc, char *argv[])
{
  char *line = NULL;
  size_t line_size = 0;
  cmd_t cmd;
  pid_t pid;
  while (1)
  {
    prompt();
    if (getline(&line, &line_size, stdin) < 0)
    {
      break;
    }
    parsed_cmd(line, &cmd);
    pid = fork();
    switch (pid)
    {
    case -1:
      perror("fork()");
      exit(1);
    case 0:
      execvp(cmd.gt.gl_pathv[0], cmd.gt.gl_pathv);
      exit(0);
    default:
      wait(NULL);
    }
  }
}

你可能感兴趣的:(implement sample shell)