Reputation: 380
I'm working on a side project where I want to spawn 5 children processes then execvp into a second program called isEven which will tell if the number passed to it is even or not. However, the execvp call keeps failing as I ran it in gdb and it doesn't execute. Args and load(args) are both called in another function.
Thanks in advance!!!
//Code to load binary
void load(char* args[])
{
execvp("./isEven", args);
printf("ERROR\n");
}
//args being passed in
char *args[] = {"./isEven", number, NULL};
load(args);
Here is a smaller program I wrote which does the same thing I'm trying to do right now. Gdb says I am getting a segmentation fault.
int main(int argc, char *argv[])
{
int returnCode = fork();
if(returnCode == 0)
{
char *args[] = {"./isEven", 12345, NULL};
execvp("./isEven", args);
printf(errno);
printf("ERROR: execvp failed\n");
exit(-1);
}
else if(returnCode < 0)
{
fprintf(stderr, "fork failed\n");
}
else
{
//i am the parent
printf("I am the parent");
}
return 1;
}
Upvotes: 0
Views: 2678
Reputation: 121357
The main problem is with this line:
char *args[] = {"./isEven", 12345, NULL};
The args
passed to execvp
must be an array of char*
. Having 12345
as an argument makes it interpret it as address and it's unlikely to be a valid address. In any case, that's not what you wanted to pass. So do:
char *args[] = {"./isEven", "12345", NULL};
You need to convert number
into a string. For example:
int number = 12345;
char num_str[256];
snprintf(num_str, sizeof num_str, "%d", number);
char *args[] = {"./isEven", num_str, NULL};
execvp("./isEven", args);
perror("exec");
In your modified example, you are printing errno
as:
printf(errno);
This will fail because printf
expects a string as its first argument. You can use perror()
to print the error as shown above.
Upvotes: 2