[英]Troubles passing arguments through execlp function - C
我正在使用給定的md5函數,當您使用文件地址輸入文件時,該函數會計算文件哈希。 問題是我需要使用fork()執行該程序,然后使用任何exe ...()函數加載它(即嘗試使用execlp()),但是當我這樣做並傳遞單個參數時,我需要計算哈希失敗。 我嘗試使用我在execlp中使用的確切參數手動運行md5程序,它不會失敗,所以我只是假設execlp參數一定有問題。 這是我用來說明情況的示例:
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
pid_t cpid;int status;
cpid = fork();
if(cpid < 0){
printf("Error fork\n");
exit (EXIT_FAILURE);
}else if (!cpid){
if (execlp("./hashMD5/me/md5","md5","testfile.a",(char*)NULL) == -1){
printf("Error: Loading process\n");
exit(EXIT_FAILURE);
}
}else{
waitpid(cpid,&status,0);
}
exit (EXIT_SUCCESS);
}
當我使用它時,我在終端出現錯誤:
$testfile.a can't be opened
但是,如果我使用完全相同的參數手動執行md5程序,則會得到正確的執行。
怎么了? 救命!
以下建議的代碼:
execl()
而不是execlp()
的正確調用,因為execl()
期望第一個參數是完整路徑,而execlp()
期望第一個參數只是文件名。 execl()
和該調用的可能失敗 perror()
正確地將錯誤消息傳遞給stderr
而不是stdout
,因此系統認為發生錯誤的原因也顯示在stderr
。 現在,建議的代碼:
#include <stdio.h> // perror()
#include <sys/types.h>
#include <stdlib.h> // exit(), EXIT_FAILURE, EXIT_SUCCESS
#include <unistd.h> // fork(), execlp()
#include <sys/wait.h> // waitpid()
int main( void )
{
pid_t cpid;int status;
cpid = fork();
if(cpid < 0)
{ // error
perror("Error fork\n");
exit (EXIT_FAILURE);
}
else if (!cpid)
{ // child
execl("./hashMD5/me/md5","md5","testfile.a", NULL);
perror("Error: Loading process\n");
exit(EXIT_FAILURE);
}
else
{ // parent
waitpid(cpid,&status,0);
}
exit (EXIT_SUCCESS);
}
我終於解決了問題。 我感謝人們給我的進步,我總是很高興學習新事物!
問題在於參數本身:即使當您使用execlp創建一個全新的進程時,參數的路徑仍然相對於父進程而言 ,這就是為什么不起作用的原因。 經過幾次頭痛之后,我終於意識到了這一點。 謝謝大家!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.