试图使用' system()'和' execv()'函数调用

时间:2018-03-30 09:24:13

标签: c linux unix exec

我想从另一个C程序执行C程序。 实际上,当控件返回到调用程序时,我需要使用system()函数来实现我的功能。由于我无法通过system()获得结果,因此我尝试使用execv(),但也未成功。

以下是我正在尝试的示例代码

int main(void) {
puts("executing this prog from another prog"); 
return EXIT_SUCCESS; 
}

以上称为test1.c

int main(void) {
execv("./test1",NULL); //system("./test1");
puts("!!!Hello World!!!"); 
return EXIT_SUCCESS; 
}

这是test2.c

使用system(),我收到sh: 1: ./test1: not found错误,而execv()只会忽略该语句并打印!!!Hello World!!!

注意:主要是我想知道system()对我想要解决的问题的运作。

1 个答案:

答案 0 :(得分:0)

execv的第二个参数必须是指向以null结尾的字符串的指针数组,更改为:

#include <unistd.h>

int main(void)
{
    char *argv[] = {NULL};
    execv("./test1", argv);
    return 0;
}

如果失败,您可以使用perror

检查错误原因
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    char *argv[] = {NULL};
    if (execv("./test1", argv) == -1) {
        perror("execv");
        exit(EXIT_FAILURE);
    }
    return 0;
}