2016-12-28 38 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

欢迎您! –