[英]execvp failing with multiple or no arguments
我正在使用C中非常基本的UNIX shell。在這個項目中,我試圖使用fork()
和execvp()
來執行實際的shell命令。 我遇到了一個問題,它似乎與具有單個參數的命令一起正常工作(例如ls -l
和echo howareyoutoday
完美地工作),但是具有多個參數的命令無法執行( echo how are you today
不跑)。 我將引導您完成我的代碼/基本原理,以幫助找出導致此問題的原因。
char *token;
int count=0;
pid_t childProc;
int childStatus;
pid_t tpid;
char* argv[256];
int i=1;
childProc = fork();
if (childProc==0) {
//CHILD PROCESS IS HERE
argv[0] = malloc(strlen(token));
argv[0] = token;
token=strtok(NULL," \n\t()<>|&;");
while(token!=NULL) {
argv[i]=malloc(strlen(token));
argv[i]=token;
token=strtok(NULL," \n\t()<>|&;");
i++;
}
execvp(argv[0],argv);
//if this executes execvp fails
printf("failure to execute\n");
i=0;
exit(0);
}
else {
//PARENT PROCESS IS HERE
do {
tpid = wait(&childStatus);
} while(tpid != childProc);
}
所以它從一個基本的fork()
調用開始創建子進程。 在那個子進程中,我為argv
數組中的第一個元素分配內存。 來自先前strtok
調用的token
被分配給argv[0]
。 生成一個新token
並將其添加到下一個argv
元素。 對剩余的剩余標記重復該過程。
完成argv
數組后,將調用execvp
,第一個參數包含命令名,第二個參數是整個argv
數組。 如果命令執行失敗, execvp
將返回並顯示一條消息,表明將打印該命令。
我無法弄清楚為什么我有上面提到的多個參數問題。 任何幫助或建議將不勝感激!
作為參考,完整程序的代碼如下:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char buffer[256];
char *token;
int count=0;
pid_t childProc;
int childStatus;
pid_t tpid;
char* argv[256];
int i=1;
int j=0;
while(1) {
fgets(buffer, 256, stdin);
token=strtok(buffer," \n\t()<>|&;");
while (token==NULL) {
fgets(buffer,256,stdin);
token=strtok(buffer," \n\t()<>|&;");
}
if (strcmp(token,"exit")==0) {
exit(0);
}
else if (strcmp(token,"cd")==0) {
token = strtok(NULL, " \n\t()<>|&;");
if (chdir(token)!=0) {
perror("Error: ");
}
}
else {
childProc = fork();
if (childProc==0) {
argv[0] = malloc(strlen(token));
argv[0] = token;
token=strtok(NULL," \n\t()<>|&;");
while(token!=NULL) {
argv[i]=malloc(strlen(token));
argv[i]=token;
token=strtok(NULL," \n\t()<>|&;");
i++;
}
execvp(argv[0],argv);
//if this executes execvp fails
printf("failure to execute\n");
i=0;
exit(0);
}
else {
do {
tpid = wait(&childStatus);
} while(tpid != childProc);
}
}
}
}
您需要將參數字符串的null終止為execvp
。
if (childProc == 0)
{
argv[0] = malloc(strlen(token));
argv[0] = token;
token = strtok(NULL, " \n\t()<>|&;");
while (token != NULL)
{
argv[i] = malloc(strlen(token));
argv[i] = token;
token = strtok(NULL, " \n\t()<>|&;");
i++;
}
argv[i] = NULL; //<--- insert here
if (execvp(argv[0], argv) == -1)
{
printf("failure to execute because %s\n", strerror(errno));
exit(0);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.