c - 在 C 中制作 shell,但无法让 chdir 工作?

标签 c linux shell command-line command

我正在用 C 编写一个 shell,它应该实现多个命令,其中之一是更改目录命令。要更改目录,我使用 chdir(),但每次运行我的代码时,我都会收到段错误(核心转储)错误。 这是我的代码:

.....
........
char *shell;
while((shell=readline("shell> ") )){
char *cmd = strtok(shell," ");

if(strcmp(cmd,"ls")==0)
 {
    //do something
 }
 else if(strcmp(cmd,"print")==0)
 {
   //do something
 }
else if(strcmp(cmd,"cd")==0){

            char *directory = strtok(NULL," ");

            if(chdir(directory)==-1){
                printf("Error\n");
            }
            else
            {
                printf("changed directories!");
            }


        }
      add_history(shell);
 }

我想我可能没有正确使用 strtok?

感谢任何帮助,谢谢:)

最佳答案

这个

    char *directory = strtok(cmd," ");

应该是

        char *directory = strtok(NULL," ");

当您调用 strtok() 获取下一个标记时,您将 NULL 传递给它。

此外,strtok() 不可重入。因此,即使您的计划是标记化不同的字符串,您也不能使用它。您可以使用 strtok_r()在 POSIX 系统上。

关于c - 在 C 中制作 shell,但无法让 chdir 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34283270/

相关文章:

mysql - 为什么 mysql 命令不能在 shell 中被字符串替换?

c++ - 发送字节数组的一部分

c - c 中的可变长度数组和静态声明

c - 打印当月日历

regex - 用 sed 替换一行但保留原始行

linux - Bash 脚本自动化

c - Makefile 难点

linux - ld : Using -rpath, $ORIGIN 在共享库中(递归)

linux - 在 debian 上创建 Chrooted 用户

Java - 执行 Shell 命令不起作用