如何使用exec()从另一个C程序运行C程序 [英] how to use exec() to run a c program from another c program

查看:54
本文介绍了如何使用exec()从另一个C程序运行C程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图使用execvp运行c程序,但是它似乎总是失败.

i've been trying to use execvp to run a c program but it always seems to fail.

来自main.c

int main() {
char* args[] = {"2", "1"};
    if(execvp("trial.c", args) == -1) {
        printf("\nfailed connection\n");
    }

来自trial.c

int main(int argc, char** argv){
printf("working");
return 1;
}

我认为我已尽一切可能在exec()中表示该文件的位置,并且总是导致连接失败".

I think i tried every way to possibly represent that file location in the exec() and it always results in "failed connection".

推荐答案

execvp 的第一个参数需要一个可执行文件的名称.您传递的是源文件的名称.您需要首先编译trial.c,然后将已编译的可执行文件的名称传递给 execvp .

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.

关于 execvp 的第二个参数,数组必须的最后一个元素为 NULL .这就是它知道它到达列表末尾的方式.同样,按照惯例,程序的第一个参数是程序本身的名称.

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.

因此,首先进行编译试验.c:

So first compile trial.c:

gcc -g -Wall -Wextra -o trial trial.c

然后修改在main.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;
}

这篇关于如何使用exec()从另一个C程序运行C程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆