#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <glob.h>
static int parse(char *linebuf, glob_t *glob_res)
{//命令如:ls -a -l /home/pxg/.. adfad
char *tok = "a";
int flag = 0;
//strtok实现
tok = strtok(linebuf, " \n");
while(tok != NULL)
{
if(tok[0] != '\0')
glob(tok, GLOB_NOCHECK|(GLOB_APPEND*flag), NULL, glob_res);
tok = strtok(NULL, " \n");
flag = 1;
}
/*while(1)
{
//strsep实现
tok = strsep(&linebuf, " \n");
if(tok == NULL)//最后一个字符'\0'解析之后就是NULL了
return 1;
if(tok[0] == '\0')//解析到最后一个字符是'\0'
continue;
glob(tok, GLOB_NOCHECK|(GLOB_APPEND*flag), NULL, glob_res);//第一次不能append,flag起作用
flag = 1;
}*/
return 1;
}
int main()
{
char *linebuf;
size_t linebuf_size = 0;
int ret = 0;
glob_t glob_res;
pid_t pid;
printf("This is shell!\n");
while(1)
{
printf("pxg /home/pxg/apue/process $ ");
getline(&linebuf, &linebuf_size, stdin);
ret = parse(linebuf, &glob_res);
if(ret == -1){
}
else if(ret == 0){//内部命令
}
else if(ret == 1){//外部命令
fflush(NULL);
pid = fork();
if(pid < 0)
{
perror("fork()");
exit(1);
}
if(pid == 0)
{
int n = 0;
for(; n < glob_res.gl_pathc; n++)
printf("%s ", glob_res.gl_pathv[n]);
execvp(glob_res.gl_pathv[0], glob_res.gl_pathv);
perror("execvp()");
exit(0);
}
}
waitpid(pid, NULL, 0);
}
exit(0);
}
李慧琴老师课程学习笔记