#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#define DIRBUF_SIZE 1024
char * readConsel(void) //从终端得到一行命令,并返回地址
{
char *ptr = NULL;
int ret;
size_t n;
ret = getline(&ptr, &n, stdin); /*若ptr=NULL,getline函数malloc出一段动态内存,故使用完后要free掉,同时ptr,n的值都会被更新*/
if (ret == -1)
{
ptr = NULL;
}
return ptr;
}
int caculateCmdNum(char *buf) //返回字符串数量
{
int i = 0, cnt = 0;
while (1)
{
if (buf[i] == 0)
break;
if (buf[i] == ' ')
{
i++;
continue;
}
else
{
if ((i != 0) && (buf[i-1] == ' '))
cnt += 1;
else if (i == 0)
cnt += 1;
}
i++;
}
return cnt;
}
int ifChdir(char **argv) /*判断是否是cd,若是执行cd操作*/
{
if (strcmp(argv[0], "cd") == 0) {
chdir(argv[1]);
return 1;
}
else
return 0;
}
void parseCommand(char *buf)
{
int ret, cnt, i = 0;
char *ptr = buf;
char *retptr = NULL;
char *delimit = " ";
cnt = caculateCmdNum(buf);
if (cnt == 0)
return;
char *argv[cnt+1];
while (1) {
retptr = strtok(ptr, delimit);
if (retptr)
argv[i++] = retptr;
else
break;
ptr = NULL;
}
argv[cnt] = NULL;
if (ifChdir(argv))
return;
pid_t pid = fork();
if (pid == -1)
{
perror("fork");
exit(-1);
}
if (pid == 0)
ret = execvp(argv[0], argv);
wait(NULL);
}
void showmyshall(void)
{
char buf[DIRBUF_SIZE];
if(getcwd(buf,DIRBUF_SIZE)==NULL)
{
perror("getcwd");
exit(-1);
}
printf("myshall:~%s$ ",buf);
fflush(stdout);
}
int main(void)
{
char *buf = NULL;
while (1) {
showmyshall();
buf = readConsel();
if (buf) {
buf[strlen(buf)-1] = '\0';
parseCommand(buf);
free(buf);
}
}
}
|