Reputation: 71
i've been trying to use execvp to run a c program but it always seems to fail.
from main.c
int main() {
char* args[] = {"2", "1"};
if(execvp("trial.c", args) == -1) {
printf("\nfailed connection\n");
}
from trial.c
int main(int argc, char** argv){
printf("working");
return 1;
}
I think i tried every way to possibly represent that file location in the exec() and it always results in "failed connection".
Upvotes: 4
Views: 9689
Reputation: 5710
If you're trying to call execvp()
on a source file then this is not what this function does. The first argument is expected to be a path of an executable. If you want to run the program which trial.c is the source of, you should build (compile and such) it first. For example like this:
$ gcc -o trial trial.c
Then call execvp()
on the your newly created executable instead of the source file:
if(execvp("trial", args) == -1) { //...
Upvotes: 0
Reputation: 12732
First argument for execvp
is path to executable.
You need to build the executable for trial.c
and pass the path of the executable to execvp
.
if(execvp("---path to executable---/ExecTrial", args) == -1) {
printf("\nfailed connection\n");
}
If you don't pass the executable path, execvp
will search the executable in the colon-separated list of directory pathnames specified in the
PATH
environment variable.
Upvotes: 1
Reputation: 223699
The first parameter to execvp
expects the name of an executable file. What you've passed it is the name of a source file. You need to first compile trial.c, then pass the name of the compiled executable to execvp
.
Regarding the second parameter to execvp
, the last element in the array must be NULL
. That's how it knows it reached the end of the list. Also, by convention the first parameter to a program is the name of the program itself.
So first compile trial.c:
gcc -g -Wall -Wextra -o trial trial.c
Then modify how to call it in main.c:
int main() {
char* args[] = { "trial", "2", "1", NULL };
if(execvp("trial", args) == -1) {
printf("\nfailed connection\n");
return 1;
}
Upvotes: 2
Reputation: 93466
trial.c is not a valid executable file. C is not a scripting or interpreted language; you cannot run C source files directly. A C program must be compiled and linked into an executable.
Upvotes: 0