[英]execvp() ls no such file or directory
我正在編寫一個shell模擬器,如果用戶鍵入“ lsh ls”,我將運行命令ls
並忽略用戶輸入的“ lsh”。 因此,我正在使用readline庫獲取輸入,然后解析該行。 然后,我使用fork()和execvp()運行ls命令。 但是,當我鍵入lsh ls
我得到以下輸出:
lsh: ls: No such file or directory
這是我的代碼。 我認為它將ls作為要搜索的文件,但是我不知道為什么要這樣做。
int main(){
pid_t id;
char* line;
char **args;
while(1){
line = readline("shell: > ");
if(strcmp(line,"exit") == 0){
break;
}
args = parse(line);
if(strcmp(args[0],"lsh") == 0){
id = fork();
if (id == 0){
if(execvp(args[1],args) < 0){
perro("no such command");
}
}
if(id > 0){
printf("I am the parent process, id %d\n",getppid());
}
}
free(line);
}
}
這是解析行的函數。
#define LSH_TOK_BUFSIZE 64
#define LSH_TOK_DELIM " \t\r\n\a"
char **parse(char *line){
int bufsize = LSH_TOK_BUFSIZE, position = 0;
char **tokens = malloc(bufsize * sizeof(char*));
char *token;
if (!tokens) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
token = strtok(line, " \n");
while (token != NULL) {
tokens[position] = token;
position++;
if (position >= bufsize) {
bufsize += LSH_TOK_BUFSIZE;
tokens = realloc(tokens, bufsize * sizeof(char*));
if (!tokens) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, LSH_TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
free(tokens);
}
您看到的錯誤消息來自ls
,而不是lsh
。
您實際上具有:
char *args[] = { "lsh", "ls", 0 };
execvp(args[1], args);
這意味着您嘗試執行ls
並成功執行,但是您將ls
稱為lsh
因為argv[0]
設置為lsh
並請求它在當前目錄中列出文件ls
。 因此,當ls
嘗試查找文件時,它會失敗,並使用您提供的命令名稱lsh
報告錯誤。
您可以嘗試一下(顯示的輸出是在macOS Sierra上獲得的):
$ cp /bin/ls xx97
$ ./xx97 23-ish
xx97: 23-ish: No such file or directory
$ rm xx97
您需要使用:
execvp(argv[1], &argv[1]);
然后,您將以常規方式調用ls
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.