简体   繁体   中英

how to use exec() to run a c program from another c program

i've been trying to use execvp to run ac 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".

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;
}

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.

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) { //...

trial.c is not a valid executable file. C is not a scripting or interpreted language; you cannot run C source files directly. AC program must be compiled and linked into an executable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM