|
文件: | myshell.c.tar.gz |
大小: | 1KB |
下载: | 下载 |
|
本程序完成基本shall功能,如ls,cd等功能。
#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);
}
}
}
|
运行结果:
zx@zhangxu:~/ad_programming/proc/homework$ ./test
myshall:~/home/zx/ad_programming/proc/homework$ ls
dup2.c myshell.c test tmp
myshall:~/home/zx/ad_programming/proc/homework$ vi tmp
myshall:~/home/zx/ad_programming/proc/homework$ cd ..
myshall:~/home/zx/ad_programming/proc$ cd homework
myshall:~/home/zx/ad_programming/proc/homework$ ^C
zx@zhangxu:~/ad_programming/proc/homework$
|
阅读(1430) | 评论(1) | 转发(1) |