【发布时间】:2014-10-17 18:56:55
【问题描述】:
您不必从头开始浏览完整的代码。问题出在 main 中的 execl(..) 语句中。代码是--
#include <cstdio>
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <vector>
#define li long int
using namespace std;
char TypedCommandInTerminal[1001];
vector <string> ValidCommands,TypedCommand;
void ShowTerminal()
{
cout<<"User:$ ";
gets(TypedCommandInTerminal);
}
void PushCommands()
{
ValidCommands.push_back("mkdir");
}
void GetCommandIntoVector()
{
TypedCommand.clear();
char *p = strtok(TypedCommandInTerminal," ");
while(p)
{
TypedCommand.push_back(p);
p = strtok(NULL," ");
}
}
bool MatchCommand(string Command)
{
li i;
for(i=0;i<ValidCommands.size();i++)
{
if(ValidCommands[i].compare(Command)==0)
{
return true;
}
}
return false;
}
int main()
{
int status;
string StoredCommand;
PushCommands();
while(true)
{
ShowTerminal();
if(fork()!=0)
{
waitpid(-1,&status,0);
}
else
{
GetCommandIntoVector();
if(MatchCommand(TypedCommand[0]))
{
StoredCommand = "mkdir";
if(StoredCommand.compare(TypedCommand[0])==0)
{
execl("/bin/mkdir","mkdir",TypedCommand[1],NULL);/*ERROR*/
}
}
else
{
cout<<"Command Not Available\n";
return -1;
}
}
}
return 0;
}
我正在尝试在 linux 中使用 c++ 设计一个简单的终端。我在这里要做的是——在控制台中将此命令作为输入——“mkdir ab”。然后我设法标记这个字符串并在 TypedCommand[0] 中保留“mkdir”,在 TypedCommand[1] 中保留“ab”。问题是当我在 execl 编译器中编写“TypedCommand [1]”时会出现错误——“无法传递非平凡可复制类型的对象.....” 我删除了 TypedCommand[1] 并手动写了“ab”来代替它。代码运行并在执行目录中创建了一个名为“ab”的文件夹。所以看起来 execl 工作正常。
我需要以某种方式在 execl 中传递保存在 TypedCommand[1] 中的第二个字符串...这里有什么问题?
【问题讨论】:
-
execl不能也不能与string对象一起使用。它适用于指向char的原始指针。至于要改变什么才能让它工作,请参阅this question。 -
@hvd 这不是 stackoverflow.com/questions/347949/… 的副本。这个问题只是关于如何将
std::string转换为const char *这个问题是关于将一个非平凡的对象传递给一个接受可变参数的函数。虽然解决方案相同,但它们是两个完全不同的问题。我敢肯定这个问题有重复,但事实并非如此。 -
@CaptainObvlious 过去,对于是否应该在另一个 question 相同或另一个问题的 answers 也回答这个问题。我关闭它是因为该问题的答案也回答了这个问题,但既然你提出来了,我已经在 Meta 上寻找相关问题,同意你的观点,并重新打开了这个问题。