[英]How to use GNU extension like wc as execvp's argument in clion?
[英]how to use execvp--finding the file argument
我編寫了一個測試程序來嘗試了解如何使用execvp(),但是我一直遇到問題。 我的代碼的相關部分是:
...
printf("execute: 'ls -a'\n");
char *args[2];
args[0] = "/bin/ls";
args[1] = "ls";
args[2] = "-a";
...
} else if(pid == 0){ //child process
if(execvp(*args, args) < 0) { //execute command
fprintf(stderr, "Error: execution failed\n");
exit(1);
}
}
...
每當我運行時,都會出現錯誤“ / bin / ls:無法訪問ls:沒有這樣的文件或目錄”。 which ls
告訴我/ bin / ls,所以我不明白我在做什么錯。 是因為可執行文件不在我的主目錄中,而是在項目文件中?
這里有幾個問題:
args
定義為2個元素的數組,但是要放入3個元素,因此要寫在數組的末尾。
args
數組的最后一個元素必須為NULL指針,否則execvp
不會知道何時到達參數列表的末尾。
args
的第一個元素應該是程序的名稱(這是在ps
清單中顯示的內容),隨后的元素應該是參數。 現在,將ls
作為數組中的第二個元素,這意味着它是命令/bin/ls
的第一個參數。 因此, ls
命令嘗試在當前目錄中找到名為ls
的文件,但找不到。 這說明了您收到的錯誤消息。
應用修復程序:
...
printf("execute: 'ls -a'\n");
char *args[3];
char *path = "/bin/ls";
args[0] = "ls";
args[1] = "-a";
args[2] = NULL;
...
} else if(pid == 0){ //child process
if(execvp(path, args) < 0) { //execute command
fprintf(stderr, "Error: execution failed\n");
exit(1);
}
}
與此處C相同的問題-嘗試將/ bin / ls傳遞給execvp時出錯
基本上,您必須使用NULL指針終止指針數組。
我真的認為代碼是
char *args[3];
args[0] = "/bin/ls";
args[1] = "-a";
args[2] = NULL;
比
char *args[2];
args[0] = "/bin/ls";
args[1] = "ls";
args[2] = "-a";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.