方法一:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wait.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t pid;
char tmp[128];
char *buf[32];
int i = 0;
while(1)
{
i = 0;
printf("root$:");
fgets(tmp,sizeof(tmp)-1,stdin);
tmp[strlen(tmp)-1] = '\0';
buf[i] = strtok(tmp," ");
if(strncmp(buf[0],"quit",4) == 0)
break;
else
printf("%s\n",buf[i]);
while((buf[++i] = strtok(NULL," ")) != NULL)
//puts(buf[i]);
buf[i] = NULL;
pid = fork();
if(pid < 0)
{
perror("fork()");
exit(1);
}
if(pid == 0)
{
execvp(buf[0],buf);
perror("execvp()");
exit(1);
}
else
{
wait(NULL);
}
}
return 0;
}
方法二:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>
#include <glob.h>
#define DELTMS " "
struct cmd_st
{
glob_t globres;
};
static void prompt(void)
{
printf("mysh-0.1$ ");
}
static void parse(char *line, struct cmd_st *res)
{
char *tok;
int i = 0;
while(1)
{
tok = strsep(&line,DELTMS);
if(tok == NULL)
break;
if(tok[0] == '\0')
continue;
glob(tok,GLOB_NOCHECK|GLOB_APPEND*i,NULL,&(res->globres));
i =1;
}
//for(i = 0;i < res->globres.gl_pathc;i++)
// puts(res->globres.gl_pathv[i]);
}
int main()
{
char *linebuf = NULL;
size_t linebuf_size = 0;
pid_t pid;
struct cmd_st cmd;
while(1)
{
prompt();
if(getline(&linebuf,&linebuf_size,stdin) < 0)
break;
linebuf[strlen(linebuf)-1] = '\0';
parse(linebuf,&cmd);
if(0) //内部命令
{
}
else //外部命令
{
pid = fork();
if(pid < 0)
{
perror("fork()");
exit(1);
}
if(pid == 0)
{
execvp(cmd.globres.gl_pathv[0],cmd.globres.gl_pathv);
perror("execvp()");
exit(1);
}
else
{
wait(NULL);
}
}
}
return 0;
}