-2

我正在编写一个批处理模拟器作为个人项目。我正在尝试使用 unistd.h 中的 chdir() 来实现 cd 命令。但是,使用它会导致段错误。

主.cpp:

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>

//Custom headers
#include "splitting_algorithm.hpp"
#include "lowercase.hpp"
#include "chdir.hpp"

//Used to get and print the current working directory
#define GetCurrentDir getcwd

using namespace std;

int main(int argc, char* argv[])
{
    string command;

    //Begin REPL code
    while (true)
    {
        //Prints current working directory
        cout<<cCurrentPath<<": ";

        std::getline(std::cin, command);

        vector<string> tempCommand = strSplitter(command, " ");

        string lowerCommand = makeLowercase(string(strSplitter(command, " ")[0]));

        //Help text
        if(tempCommand.size()==2 && string(tempCommand[1])=="/?")
        {
            cout<<helpText(lowerCommand);
        }

        //Exit command
        else if(lowerCommand=="exit")
        {
            return 0;
        }
        else if(lowerCommand=="chdir")
        {
            cout<<string(tempCommand[1])<<endl;
            chdir(tempCommand[1]);
        }

        else
            cout<<"Can't recognize \'"<<string(tempCommand[0])<<"\' as an internal or external command, or batch script."<<endl;
    }
    return 0;
}

chdir.cpp:

#include <cstdlib>
#include <string>
#include <unistd.h>

void chdir(std::string path)
{
    //Changes the current working directory to path
    chdir(path);
}

奇怪的是,使用 cout 获取 chdir 的路径工作得非常好。我该如何解决?

4

2 回答 2

3

You have recursive, unterminated behaviour in Your code. This overflows the stack.

Try to insert breakpoint in void chdir(std::string path) and see what happens.

You will see that the function chdir calls itself, and in turn calls itself again, and again and... well, segmentation fault.

Also, try to see what "call stack" is in the debugger, this issue is very visible there.

于 2015-06-18T07:11:16.060 回答
2

您应该使用调用底层 chdir 函数

::chdir(path.c_str());

或者你会再次调用你自己的方法。

在 unistd.h 中,chdir 定义为:

int chdir(const char *);

所以你必须用一个const char*参数调用它,否则编译器将搜索另一个名为“chdir”的函数,它接受一个std::string参数并使用它。

于 2015-06-18T07:12:24.417 回答