我有一个 C++ 程序,在程序中的某个时刻我需要调用一个 C 程序并向其传递一些参数。
我在linux环境中工作。
文件 simpsh 是同一目录中编译后的 c 文件。 result_simpsh_command 是包含此类型数据的字符串 --creat --trunc --wronly f1 到目前为止。
当我检查在 C 程序中收到的值时,它会显示此内容
void execute_simpsh(string resulting_simpsh_command)
{
pid_t pid = fork();
if(pid == -1)
perror("Fork failed!");
else if(pid ==0)
{
char* args[256];
string simpsh ="./simpsh";
args [0] = (char*) simpsh.c_str();
string temp_option_holder="";
int nextCommand=1;
for(int i=0;i<resulting_simpsh_command.length();i++)
{
if(resulting_simpsh_command[i] !=' ')
{
temp_option_holder += resulting_simpsh_command[i];
}
else
{
cout<<"saving to argument: "<<temp_option_holder<<endl;
args [nextCommand] = (char*) temp_option_holder.c_str();
temp_option_holder="";
nextCommand +=1;
}
}
cout<<"command numbers "<<nextCommand<<endl;
args [nextCommand + 1] = NULL;
if(execvp(args[0],args) == -1)
cout<<"Failed to open simpsh, maybe you didnt compile?"<<endl;
exit(1);
}
else
{
//not important for now
}
}
最佳答案
由于您(错误)使用了 c_str
,许多 args
数组将成为无效指针。
一旦字符串的缓冲区被重新分配,指针就会变得无效。
一些 args
指针也可能指向相同的东西,即使它们是有效的。
解决此问题的两个选项(我的脑海中浮现出):
动态分配:
args[nextCommand] = strdup(temp_option_holder.c_str());
这需要稍后释放。
或者,如果您可以接受限制参数长度,则可以使用另一个数组并避免内存管理(但您需要担心溢出):
char arg_strings[256][ARGUMENT_LENGTH] = {0};
char* args[256] = {0};
// ...
assert(temp_option_holder.length() < ARGUMENT_LENGTH);
strncpy(arg_strings[nextCommand], temp_option_holder.c_str(), ARGUMENT_LENGTH);
args[nextCommand] = arg_strings[nextCommand];
关于c++ - 从 C++ 调用 C 程序并传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266731/