2016-12-28 55 views
0

我遇到了execve命令有點問題。程序測試應該創建兩個孩子,每個孩子應該運行一個execve來加載和運行另一個程序。但是,我在這兩個execve上都收到了不好的地址。代碼如下:Execve給出錯誤的地址

#include <stdlib.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <string.h> 
#include <sys/stat.h> 
#include <errno.h> 
#include <time.h> 
#include <sys/ipc.h> 
#include <sys/types.h> 
#include <sys/wait.h> 

int main(){ 
    int child_1, child_2; 

    child_1=fork(); 
    if(child_1==0){ 
     char* argv[]={"Test", "Test_1", "NULL"}; 
     if((execve("Test_1", argv, NULL))<0) perror("execve 1 fail"); 
     exit(0); 
    }else if(child_1<0)perror("error fork"); 
    else wait(NULL); 

    child_2=fork(); 
    if(child_2==0){ 
     char* argv1[]={"Test", "Test_2", "NULL"}; 
     if((execve("Test_2", argv1, NULL))<0) perror("execve 2 fail"); 
     exit(0); 
    }else if(child_2<0)perror("error fork"); 
    else wait(NULL); 
return 0; 
} 
+0

它不會導致錯誤*本身*,但是在第二個分支前等待(')第一個孩子是可疑的。如果這兩個孩子是按順序運行的,那麼就是這樣做的方法,但如果他們想要同時運行,那麼父母不應該等到分岔了兩個孩子之後。 –

+0

感謝您的提示。它應該同時工作,所以我會嘗試你的建議。 – Leo

回答

4

你是不是正確終止參數數組:

char* argv[]={"Test", "Test_1", "NULL"}; 

"NULL"是一個字符串,它不一樣NULL。該數組需要用空指針終止。相反:

char* argv[]={"Test", "Test_1", (char*)0}; 

同樣,修復另一個參數數組。

+0

感謝您的快速回復,現在可以使用。 – Leo

+0

歡迎您! –