用于执行shell指令的shell代码

时间:2016-03-18 13:03:44

标签: c shell

我想在我的代码中执行像shell一样的cd命令... 我的代码将向用户询问整个命令,如“cd / desktop”,我尝试使用chdir(路径),但在我的代码中执行cd的部分错误...请帮助

void main(void) {
    char in[512];
    pid_t id;
    int status,x,y,i = 1;
    char *f[512];
    char *v;
    char *s;

    while(1)
    {
        printf("shell>");

        fgets(in,512, stdin);
        int size = strlen(in);// calculate dim of in execpt null
        in[size-1] = '\0'; //null at the end because ls\n not executable
        v = strtok(in, " ");
        f[0] = v;
        while (v = strtok(NULL, " ")){
            f[i] = v;
            i++;
        }
        f[i] = NULL;

         y=strcmp(f[0],"exit");      
         if(y==0)
             break;

         x=strcmp(f[0],"cd");
         if(x==0){
             s=f[2]; // this should be the path is it right?
             chdir(s);
         }

         id=fork();

         if (id==0){ //child
             execvp(f[0],f);
             perror("failure");
             exit(1);
         }
         else //parent
         {
             waitpid(id,&status,0);
         }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你至少应该移动

i = 1;

进入while循环,即

while(1)
{
    i = 1;

另外

s=f[2]; // this should be the path is it right?

我希望它是f[1]

基于您的代码的示例

#include <string.h>
#include <stdio.h>

int main(void) {
    char in[512];
    int status,x,y,i = 1;
    char *f[512];
    char *v;
    char *s;
    char cwd[1024];  // ADDED THIS

    while(1)
    {
        i = 1;  // ADDED THIS

        getcwd(cwd, sizeof(cwd));        // ADDED THIS - print current dir
        fprintf(stdout, "%s - ", cwd);

        printf("shell>");

        fgets(in,512, stdin);

        printf(" %s", in);   // ADDED THIS

        int size = strlen(in);// calculate dim of in execpt null
        in[size-1] = '\0'; //null at the end because ls\n not executable
        v = strtok(in, " ");
        f[0] = v;
        while (v = strtok(NULL, " ")){
            f[i] = v;
            i++;
        }
        f[i] = NULL;

         y=strcmp(f[0],"exit");      
         if(y==0)
             break;

         x=strcmp(f[0],"cd");
         if(x==0){
             s=f[1];         // CHANGED THIS
             printf("path=%s\n", s);  // just a print for debug
             //chdir(s);              // just removed for debug
         }
    }
    return 0;
}

输入:

  

cd dir1

     

cd dir2

     

出口

输出:

  

壳&GT; cd dir1

     

路径= DIR1

     

壳&GT; cd dir2

     

路径= DIR2

     

壳&GT;出口