Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execve is giving bad address

Tags:

c

I'm having a little problem with the execve command. The program Test should create two children and each one should run an execve to load and run another program. But I'm getting a bad address on both the execve. The code is as follows:

#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;
}
like image 928
Leo Avatar asked Dec 03 '22 23:12

Leo


2 Answers

You are not terminating the argument array correctly:

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

"NULL" is a string literal, it's not same as NULL. The array needs to be terminated with a null pointer. Instead do:

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

Similarly, fix the other argument array.

like image 104
P.P Avatar answered Dec 11 '22 16:12

P.P


or you have to change "NULL" to simply NULL. In the case "NULL" you give NULL as a commandline parameter. The case NULL without " means end of argument list.

like image 27
Agguro Avatar answered Dec 11 '22 17:12

Agguro