![](/img/trans.png)
[英]I've made two codes but I can't interpret why these two are different and produce different results
[英]Why do these two execvp produce different results?
我想知道為什么以下內容會產生不同的結果:
char *const temp[] = {"cal","4","2019",NULL};
execvp(temp[0],temp);
perror("Return from execlp not expected");
exit(EXIT_FAILURE);
執行時將產生一個日歷,其中僅包含一個月的四月
char *const temp[] = {"cal"};
char *const temp2[] ={"4","2019",NULL};
execvp(temp[0],temp2);
perror("Return from execlp not expected");
exit(EXIT_FAILURE);
執行時將產生一個包含所有月份的日歷
我想讓第二種形式正常工作,因為我的問題是我有2個數組,一個數組存儲我的所有命令,另一個數組存儲我的所有命令參數。 例如
array1[0] = command
array2[0] = arg1 ar2 arg3 // the arguments for the command in array1[0]
在一個循環中,直到我到達命令數組的末尾為止,使用fork並在子類中執行這些命令,以便我可以遍歷並執行數組中的所有命令。
int execvp(const char *file, char *const argv[]);
execv(),execvp()和execvpe()函數提供了一個指向以空字符結尾的字符串的指針的數組,這些字符串表示新程序可用的參數列表。 按照慣例,第一個參數應指向與正在執行的文件關聯的文件名。 指針數組必須以NULL指針終止
argv[0]
始終被認為是程序的名稱,即使execvp
不使用它,就像您的情況一樣。 cal
程序本身開始從argv[1]
解釋命令行。 (請參閱@kiran Biradar答案。)
您需要將(指針指向)參數復制到更大的數組中,並為argv[0]
設置一個虛擬參數。 這是一些簡短的代碼可以做到這一點:
char **combine_args(char *arg0, char **tail) {
size_t n = 0;
while(tail[n]) ++n;
char **ret = malloc(sizeof(char*)*(n+2));
ret[0] = arg0;
memcpy(ret + 1, tail, sizeof(char*)*n);
ret[n+1] = 0;
return ret;
}
接下來,您可以像這樣使用它:
char *const temp[] = {"cal"};
char *const temp2[] ={"4","2019",NULL};
char **argv = combine_args(temp[0], temp2);
execvp(argv[0], argv);
perror("Return from execlp not expected");
exit(EXIT_FAILURE);
如果您循環執行此操作,並且可以更改temp2
數組,則可以像這樣進行操作,而無需進行任何分配:
char *const temp[] = {"cal", "cal2", "cal3", NULL};
char *temp2[] ={NULL, "4","2019",NULL};
for(int i = 0; temp[i]; ++i)
{
// ... fork here ...
{
temp2[0] = temp[i];
execvp(temp2[0], temp2);
perror("Return from execlp not expected");
exit(EXIT_FAILURE);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.