简体   繁体   English

Unix中的C ++ Shell,execv:从函数动态创建并返回可用的第二个参数

[英]C++ Shell in Unix, execv: Dynamically create and Return a usable second parameter from a function

Everywhere I've looked for answers to this question, I see people making one small char * array of size like two and hardcoding in paths for execv. 我到处都在寻找这个问题的答案,我看到人们制作一个小的char *数组,大小类似于2,并在execv的路径中进行硬编码。 What I need to do is to take a string of parameters with the path as the first set of characters, tokenize them, and then put them in an array of char *s that execv will accept. 我需要做的是获取参数字符串,并将路径作为第一组字符,将它们标记化,然后将它们放入execv将接受的char * s数组中。

here is my tokenization function 这是我的标记功能

char ** stringToVectorToCharArray(string inputString)
{
stringstream ss(inputString);
cout << "\n inputString is: " << inputString <<"\n";
vector<string> tokens;
tokens.clear();

while(ss >> inputString)
{
    tokens.push_back(inputString);
    }


int size = tokens.size();       
char **args = new char*[size + 1];

int i = 0;
for(; i < size; i++)
    args[i] = const_cast<char *>(tokens.at(i).c_str());

args[i + 1] = (char *) 0;

return args;
}

And this is called from 这是从

 char **args = stringToVectorToCharArray(inputString);

 execv(executeChar, args);

Within the Child section of my fork() if-else statements for flow control. 在我的fork()if-else语句的Child部分中,用于流控制。 I get a bad_alloc error, but I'm not sure which of my allocation statements are right, if any are for that matter. 我收到bad_alloc错误,但是我不确定哪个分配语句正确(如果有的话)。 I know the return has to be in the form 我知道退货必须采用以下形式

 char *const argv[]

But I'm not sure how to set that up. 但是我不确定如何设置。

You are returning memory from a local variable ( tokens ) from your function. 您正在从函数的局部变量( tokens )返回内存。

for(; i < size; i++) {
  // stores pointer to local memory: args[i] = const_cast<char *>(tokens.at(i).c_str());
  args[i] = new char[tokens.at(i).size()+1];  // Create dynamically allocated copy
  strcpy(args[i], tokens.at(i).c_str());
}

The above should fix the problem. 以上应该可以解决问题。 Technically, this would create a memory leak, since the memory is never deallocated, but your call to execv will replace your executable and effectively deallocate the memory. 从技术上讲,这将导致内存泄漏,因为从不释放内存,但是您对execv将替换您的可执行文件并有效地重新分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM