EXEC() 的 C 替代方案来支持参数?

C Alternatives of EXEC() to Support Arguments?

在 C 中,我知道传递给程序的参数从索引 1 开始。 假设第一个参数(在索引 1 中)是一些任意文本,程序 location/name 中的参数 2,所有其他参数都是该程序的参数(我不知道任何限制)

在我 fork 了一个子进程之后,我怎样才能使它成为 运行 那个程序?

这是我过去在没有传递参数时所做的示例:

int main (int argc, char *argv[]){
    run_prog(argv[2]);
}

void run_prog(char *prog_name)
{
    execl(prog_name, prog_name, NULL);
}

这就是我过去运行的方式:

./my_prog ignore_this hello_world.out

您可以使用 exec 调用系列的 execv 变体。来自 execv man page:

The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.

由于 argv 已经是所需格式的数组,您需要做的就是跳过您不感兴趣的参数:

void run_prog(char *argv[])
{
    execv(argv[2], &argv[2]);
}

int main (int argc, char *argv[])
{
    run_prog(argv);
}