C ++主调用execvp函数在调用ls或ls -l时给出错误

问题描述

我必须编译一个minishell的main.cpp并处理ls,ls -l,pwd,cat等函数,因为这是使用fork和exec的,但是我现在被卡住了。子进程和父进程运行。我将命令保存在* args中。

char* args[com.numArgs() + 1];
cout << ">>>> ";
com.read();
cout << num++ << ")" << com << endl; //prompt for next command

for (int i = 0; i <= com.numArgs(); i++)
{
    args[i] = (char*)com.args()[i].c_str();
}// makes array of commands 
    while (com.name() != "exit") // exits mini-shell
{
    if (com.name() == "cd")
    {
        string dir_name;
        dir_name = args[1];
        int p = chdir(dir_name.c_str());

        if (p == -1)     //checking dir
        {
            cout << "dir not changed";
        }
        else
        {
            cout << "dir changed" << endl;
        }
    }
    else
    {
pid = fork();    //generate process
        if (pid != 0) {
        cout << "we are in parent" << pid << " " << getpid() << endl;
        waitpid(pid,NULL,0);
        cout << "child process excuted" << endl;
        
        }

        else if (pid ==0)//in child
        {
            cout << "Child" << pid << " " << getpid() << endl;
            cout << "run exec here" << endl;
            execvp(args[0],args);
            cout << "execvp Failed ! " << endl;
        }
    }

输出

> project]$ ./proj1
>>>> ls
0)ls 
ls

we are in parent20265 20264
Child0 20265
run exec here
ls: cannot access '': No such file or directory
child process excuted

但是,如果我先做cd ..那就行了

>>> cd ..

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)