Shell 无法转换‘;常量字符*’;至‘;字符*常量*’;
我正在尝试实现一个shell。我将创建一个hist数组来存储最后10个命令,我希望以后能够检索这些命令以便执行。因此,我试图找到一种方法,在我将所有命令行参数存储到hist数组中后,将它们取回 提供的一些代码gettoks()是一个函数,用于获取和解析输入的命令行。函数gettoks()返回指向字符串的指针数组。每个字符串要么是包含字母、数字和/的单词,要么是包含一个特殊字符的单个字符串:()<>|& 我知道我可以将toks传递给execvp,以便在执行命令后立即执行该命令,但一旦它存储在字符串的2d数组中,我将如何检索它 我也明白指针和数组可以让我的生活更轻松,但我还是不太熟悉它们!所以,我想知道我是否可以得到一些关于代码的反馈,并解决第“execvp(c[0],c);”行的编译错误 “错误:从'char'到'const char*'的转换无效” 错误:无法将参数“2”的“const char*”转换为“char*const*”,将其转换为“int execvp(const char*,char*const*)” 多谢各位Shell 无法转换‘;常量字符*’;至‘;字符*常量*’;,shell,execvp,Shell,Execvp,我正在尝试实现一个shell。我将创建一个hist数组来存储最后10个命令,我希望以后能够检索这些命令以便执行。因此,我试图找到一种方法,在我将所有命令行参数存储到hist数组中后,将它们取回 提供的一些代码gettoks()是一个函数,用于获取和解析输入的命令行。函数gettoks()返回指向字符串的指针数组。每个字符串要么是包含字母、数字和/的单词,要么是包含一个特殊字符的单个字符串:()|& 我知道我可以将toks传递给execvp,以便在执行命令后立即执行该命令,但一旦它存储在字符串的2
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <cstdlib>
#include <stdio.h>
using namespace std;
extern "C"
{
extern char **gettoks();
}
int main( int argc, char *argv[] )
{
// local variables
int ii;
char **toks;
int retval;
string tokenString;
string hist[11][2];
// initialize local variables
ii = 0;
toks = NULL;
retval = 0;
tokenString = "";
int m = 0; // command counter
for(int i = 0; i < 11; i++){ // initialize the hist array
for (int j = 0; j <2; j++){
hist[i][j]= "";
}
}
// main (infinite) loop
while( true )
{
// get arguments
toks = gettoks();
if( toks[0] != NULL ){ // if a command is entered
if ( m < 10){
m++; // increment the number of commands
for( ii=0; toks[ii] != NULL; ii++ ){ // add the command to the hist array
tokenString += toks[ii];
}
hist[m][0] = toks[0];
hist[m][1] = tokenString;
}
else if (m == 10){ // if the hist array is full
for( int k = 1; k < 10; k++ ){ // shift the commands in the hist array
for (int l = 0; l < 2; l++){
hist[k][l] = hist[k+1][l];
}
}
for( ii= 0; toks[ii] != NULL; ii++ ){ // add the new command to the hist array
tokenString += toks[ii];
}
hist[10][0] = toks[0];
hist[m][1] = tokenString;
}
}
for(int i = 1; i < 11; i++){// print the hist array
for (int j = 0; j <2; j++){
cout << hist[i][j] << "\t";
}
cout << endl;
}
tokenString = ""; // reset
const char * c = hist[1][1].c_str();
execvp(c[0] , c);
if( !strcmp( toks[0], "exit" ))
break;
}
// return to calling environment
return( retval );
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
外部“C”
{
外部字符**gettoks();
}
int main(int argc,char*argv[])
{
//局部变量
int ii;
char**toks;
内部检索;
字符串标记字符串;
字符串历史[11][2];
//初始化局部变量
ii=0;
toks=NULL;
retval=0;
标记字符串=”;
int m=0;//命令计数器
对于(inti=0;i<11;i++){//初始化hist数组
for(int j=0;jexecvp
的用法如下:
char* cmd[] = { "sleep", "1", NULL };
execvp(cmd[0], cmd);
但是在您的代码中,您正在传递c
,这是一个常规的c字符串(const char*
)。您可以将gettoks()
函数返回的数组直接与execvp
一起使用