分类: LINUX
2012-05-22 15:25:57
#include
#include
#include
#include
#include
#include
#include
#include
char cmd[128]; //the path when opening the shell
char cmd_buf[256]; //store the parameters
char *cmd_argv[128]; //store the parameters' array subscript
int getfrontdir(char buf[]) //get the front dir
{
int i,j = 0;
for ( i = 0 ; buf[i] != '\0' ; i ) {
if ( buf[i] == '/' ) {
j = i;
}
}
if ( j == 0)
j = 1;
return j;
}
int getdir() //get the dir
{
struct passwd *pwd;
pwd = getpwuid(getuid());
int i;
char buf[256];
if (strcmp(cmd_argv[0],"cd") == 0) {
getcwd(buf,256);
if ( cmd_argv[1] == NULL ) {
strcpy(buf,pwd->pw_dir);
chdir(buf);
}
else {
if ( strcmp(cmd_argv[1],"..") == 0 ) {
i = getfrontdir(buf);
buf[i] = '\0';
chdir(buf);
}else {
strcpy(buf,cmd_argv[1]);
if ( chdir(buf) == -1 )
fprintf(stderr,"%s:%s\n",cmd_argv[0],strerror(errno));
}
}
return 1;
}else {
return 0;
}
}
void FORK() //make a child pid ,then do the cmd
{
pid_t pid;
if ( (pid = vfork()) == -1 ) {
perror("fork");
exit(-1);
}
if ( pid > 0 ) {
int i;
wait(&i);
}
else {
if ( execvp(cmd_argv[0],cmd_argv) == -1 ) {
perror("execvp");
exit(1);
}
}
}
void Get() //get the string which is write on the gnome
{
int c;
int i = 0, j = 0;
while ( (c = getchar()) != '\n' ) {
if ( c == ' ') {
cmd_buf[i ] = '\0';
}else {
if ( cmd_buf[i-1] == '\0' ) {
cmd_argv[j ] = cmd_buf i;
}
cmd_buf[i ]=c;
cmd_buf[i] = '\0';
}
}
cmd_argv[j] = NULL;
}
void main_loop() //the main
{
int i = 0;
strcpy(cmd,"Myshell:");
char path[128];
getcwd(path,128);
strcat(path,"$ ");
strcat(cmd,path);
printf("%s",cmd);
fflush(stdout);
Get();
if ( strcmp(cmd_argv[0],"exit") == 0 ) {
exit(0);
}
else {
i = getdir();
if ( i != 1 ) {
FORK();
}
}
bzero(cmd,128);
}
int main(int argc,char **argv)
{
while(1) {
main_loop();
}
return 0;
}