2014-12-03 24 views
0

我想了解如何實現execv()代替execvp()Execv()的實現,而不是execvp()

我有有execvp(代碼),我嘗試將其轉換成execv( )但我失敗了,因爲我找不到命令的路徑。 哪條命令獲取文件我想的路徑,但我怎麼能實現它在execv()

我想這個代碼轉換:

if ((pid = fork()) < 0) {  /* fork a child process   */ 
     printf("*** ERROR: forking child process failed\n"); 
     exit(1); 
} 
else if (pid == 0) {   /* for the child process:   */ 
    printf("hophop"); 
    if (execv("/usr/bin/ls"+*args[0], args) < 0) {  /* execute the command */ 
     printf("*** ERROR: exec failed\n"); 
     exit(1); 
    } 
} 
else {         /* for the parent:  */ 
    while (wait(&status) != pid)  /* wait for completion */ 
     ; 
} 
/** the steps are: 
    (1) fork a child process using fork() 
    (2) the child process will invoke execvp() 
    (3) if background == 0, the parent will wait, 
    otherwise it will invoke the setup() function again. */ 
+1

這一行:'while(wait(&status)!= pid)'應該是:'wait(&status);' – user3629249 2014-12-04 00:05:24

+0

你確定'ls'二進制文件位於系統中的'/ usr/bin /'中嗎? '哪些ls'說什麼? – xbug 2014-12-04 00:08:47

+0

這一行:'if(execv(「/ usr/bin/ls」+ * args [0],args)<0){'不會將正確的格式發送到execv()。 ls命令的任何參數必須位於args中,其中args的定義如下所示:char ** args [];並且該數組中的最後一項必須爲NULL – user3629249 2014-12-04 00:09:31

回答

1

execvp搜索命令中的目錄列表在PATH環境變量中。

如果要複製execvp的功能getenv(「PATH」),請將字符串拆分爲單獨的目錄(以冒號分隔的字符串),然後搜索列表中的每個目錄,直至找到可執行文件,然後execv()它。

如果你有一個可執行文件名這已經開始與/字符的絕對路徑,跳過搜索部,當然,;在這種情況下,execvp等同於execv。

相關問題