2014-10-19 32 views
0

我一直在困惑這一段時間,現在我可以使用一些幫助。 我試圖創建一個循環,將叉掉一個子進程,並通過execve()調用「echo hello」。execve()只在第一個循環返回錯誤

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/wait.h> 

int main(int argc, char *argv[],char *envp[]){ 

    int i = 0; 

    while(i<10){ 
    pid_t pid; 
    pid = fork(); 

    if(pid != 0){ 
     int status; 
     waitpid(-1, &status, 0); 
    } 

    if(pid == 0) { 
     char *arg_array[2]; 
     arg_array[0]="echo"; 
     arg_array[1]="hello"; 
     char filename[] = "/bin/echo";  
     if (execve(filename,arg_array,envp) == (-1)) { 
     printf("ERROR!\n"); 
     exit(1); 
     } 
    } 
    i++; 
    } 
} 

起初,代碼在第一次運行時失敗,並且在後續的每次運行中都成功執行。 現在,清理後在這裏展示,它根本不會成功 - 我得到的只是錯誤! ×10.我一定已經打破了一些東西,我不能說出什麼。

這只是我在這個網站上的第二個問題,所以如果你有任何建議來改善我的問題/建設性的批評,請分享!謝謝。

回答

0

您錯過了argv陣列的最後一個NULL元素。在execve之後使用perror也會給你正確的錯誤信息。因此:

char *arg_array[3]; arg_array[0] = "echo"; arg_array[1] = "hello"; arg_array[2] = NULL;

此外,你缺少#include <unistd.h>

+0

哈!這解決了它!精彩。 unistd.h做了什麼?沒有它似乎工作得很好。 – Hal 2014-10-19 16:57:22

+0

閱讀給定函數的文檔並查看哪個標準頭文件聲明它總是有用的。在我的系統上,我收到了關於隱式聲明的警告。也許在你的系統''中會自動包含'',但事實並非總是如此。 – 2014-10-19 16:58:32

+0

謝謝,我現在看到。我仍然是一個初學者,所以儘管我看了文檔,但我不太清楚''做了什麼。 – Hal 2014-10-19 17:05:22