2015-04-07 111 views
0

我在C++中遇到execvp()问题。这里是我的代码:如何使execvp()处理多个参数?

char * argv[]={}; 
command_counter = 0; 
char line[255]; 
fgets(line,255,stdin); 

argv[0] = strtok(line, TOKEN);//seperate the command with TOKEN 




while (arg = strtok(NULL, TOKEN)) { 
     ++command_counter; 
     cout << command_counter << endl; 
     argv[command_counter] = arg; 
     cout << argv[command_counter] << endl; 
    } 
argv[++command_counter] = (char *) NULL; 
execvp(argv[0],argv); 

但问题是,当我使用execvp()这样的多个参数不工作。

ls -a -l一样,它仅作为结果执行ls -a

这个程序有什么问题?

有了你们的问题,通过改变的char * argv的声明解决的问题[128]

+2

废话 - 'execvp() '处理非常大量的参数没有问题。你用'execvp()'的方式遇到了问题。你可以通过将你的问题描述为“如何正确使用'execvp()',因为这不起作用”而不是''execvp()'不起作用“来帮助你。我已经或多或少的在这个问题上为你解决了这个问题的措辞,但是这次你会发现你错误的频率比系统更高。 –

+1

'char * argv [] = {};'你认为这会做什么? – Gopi

+1

因为你的行长度为255个字符,所以不能超过128个参数,所以你应该写:'char * argv [128];'。 –

回答

2

第一件事是错了,是你正在创建一个零大小的数组存储参数:

char * argv[]={}; 

然后填充它。

这是一个很大的未定义的行为红旗就在那里。

一个快速和肮脏的解决将是确保你有一定的空间有:

char * argv[1000]; 

但是,说实话,有其自身的问题,如果你有机会到这种地步,可能比一个更一千个参数。底线是,你应该确保在数组中有足够的空间来存储你的参数。这样做的


一个方法是使用动态内存分配,按照需要扩展的参数数组,这样才能保证始终有足够的空间:

using namespace std; 

#include <iostream> 
#include <cstring> 
#include <cstdlib> 
#include <cstdio> 
#include <unistd.h> 

#define TOKEN " " 

static char **addArg (char **argv, size_t *pSz, size_t *pUsed, char *str) { 
    // Make sure enough space for another one. 

    if (*pUsed == *pSz) { 
     *pSz = *pSz + 25; 
     argv = (char **) realloc (argv, *pSz * sizeof (char*)); 
     if (argv == 0) { 
      cerr << "Out of memory\n"; 
      exit (1); 
     } 
    } 

    // Add it and return (possibly new) array. 

    argv[(*pUsed)++] = (str == 0) ? 0 : strdup (str); 
    return argv; 
} 

int main (void) { 
    Initial size, used and array. 

    size_t sz = 0, used = 0; 
    char **argv = 0; 

    // Temporary pointer and command. 

    char *str, line[] = "ls -a -l"; 

    // Add the command itself. 

    argv = addArg (argv, &sz, &used, strtok (line, TOKEN)); 

    // Add each argument in turn, then the terminator. 

    while ((str = strtok (0, TOKEN)) != 0) 
     argv = addArg (argv, &sz, &used, str); 

    argv = addArg (argv, &sz, &used, 0); 

    // Then execute it. 

    execvp (argv[0], argv); 

    // Shouldn't reach here. 

    return 0; 
} 
+0

感谢问题解决.. –