将参数字符串传递给 execvp
Passing parameters a a string to execvp
我有以下代码:
int main(int argc, char *argv[])
{
int i, a=9;
int length = 0;
const char fail[20] = "Missing Arguments\n";
char s1[512] = "";
char s2[15] = "./calc_prizes";
for (i=1; i<argc; i++) {
length += sprintf(s1+length, " %s", argv[i]);
}
strcat(s2, s1);
while(++a < argc) {
if(fork() == 0) {
char* arg[] = {s2, s1, NULL}; //this is the part that's wrong
execvp(arg[0],arg);
exit(1);
}
else
wait(NULL);
}
return 0;
}
s2存放程序名称,s1参数收集参数。我似乎无法 运行 带有 execvp 参数的程序,我做错了什么?
execvp
失败的一个可能原因可能是:
strcat(s2, s1);
[我希望你已经确保 s2
足够大以包含连接的结果字符串,否则它的缓冲区溢出,这是一个不同但肯定是你的代码中的问题。]
在这里,您将 s1
连接到 s2
,s2
是您要执行的程序的名称。在 while
循环中,您正在做:
char* arg[] = {s2, s1, NULL};
arg[0]
指向 s2
(连接的字符串)并且您将其作为第一个参数传递给 execvp
:
execvp(arg[0],arg);
The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer. [emphasis mine]
因此,要成功调用 execvp
,您应该将第一个参数作为可执行文件的名称,在您的情况下为 ./calc_prizes
。
我有以下代码:
int main(int argc, char *argv[])
{
int i, a=9;
int length = 0;
const char fail[20] = "Missing Arguments\n";
char s1[512] = "";
char s2[15] = "./calc_prizes";
for (i=1; i<argc; i++) {
length += sprintf(s1+length, " %s", argv[i]);
}
strcat(s2, s1);
while(++a < argc) {
if(fork() == 0) {
char* arg[] = {s2, s1, NULL}; //this is the part that's wrong
execvp(arg[0],arg);
exit(1);
}
else
wait(NULL);
}
return 0;
}
s2存放程序名称,s1参数收集参数。我似乎无法 运行 带有 execvp 参数的程序,我做错了什么?
execvp
失败的一个可能原因可能是:
strcat(s2, s1);
[我希望你已经确保 s2
足够大以包含连接的结果字符串,否则它的缓冲区溢出,这是一个不同但肯定是你的代码中的问题。]
在这里,您将 s1
连接到 s2
,s2
是您要执行的程序的名称。在 while
循环中,您正在做:
char* arg[] = {s2, s1, NULL};
arg[0]
指向 s2
(连接的字符串)并且您将其作为第一个参数传递给 execvp
:
execvp(arg[0],arg);
The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer. [emphasis mine]
因此,要成功调用 execvp
,您应该将第一个参数作为可执行文件的名称,在您的情况下为 ./calc_prizes
。