c - 用于执行shell指令的shell代码

标签 c shell

我想在我的代码中像 shell 本身一样执行 cd 命令... 我的代码将询问用户整个命令,如“cd/desktop”,我尝试使用 chdir(path),但在我的代码中执行 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);
         }
    }
}

最佳答案

我认为你至少应该搬家

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

exit

输出:

shell> cd dir1

path=dir1

shell> cd dir2

path=dir2

shell> exit

关于c - 用于执行shell指令的shell代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36085139/

相关文章:

linux - 如何检查文件中存在的子字符串?

c - fnmatch 模式匹配

c - 如何使用 Vlang 中的 C 库进行基本统计

c - 使用c从单板计算机写入mysql数据库

c - 为什么代码会抛出段错误?

windows - 当路径包含哈希时,导航 Shell 命令不起作用

shell - 如何grep和匹配一行的第一次出现?

linux - 使用shell脚本修改/etc/hosts文件

php - 在 php 上运行 exec 命令

python - 在 python 中使用 Windows shell '>' 将输出重定向到文本文件