美文网首页
implement sample shell

implement sample shell

作者: perryn | 来源:发表于2019-06-20 22:23 被阅读0次
  • sample shell
/*************************************************************************
  > File Name: shell.c
  > Author:perrynzhou 
  > Mail:perrynzhou@gmail.com 
  > Created Time: Thu 20 Jun 2019 09:15:59 PM CST
 ************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <glob.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
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

      本文链接:https://www.haomeiwen.com/subject/wbmsqctx.html