gpt4 book ai didi

c - 执行 : how can I initialise char *argv[ ] with multiple commands instead of a single command?

转载 作者:IT王子 更新时间:2023-10-29 01:20:48 26 4
gpt4 key购买 nike

execve:如何使用多个命令而不是单个命令来初始化 char *argv[ ]
如果我想执行4条命令,可以使用下面的语句吗?

char *argv[4][ ] = { {...}, {...}, {...} };

要使用 execve 执行它们,我可以使用 var 从 1 到 4 的循环吗?

最佳答案

您不能仅通过一个execve 调用来执行多个命令。在一个循环中,您需要fork 您的程序以执行多个execve 调用。在manpage of execve是这样写的:

execve() does not return on success, and the text, data, bss, and stack of the calling process are overwritten by that of the program loaded. [...]

Return value
On success, execve() does not return, on error -1 is returned, and errno is set appropriately.

使用fork的方法:

输出:

Hello 1
Hello 2
Hello 3

代码:

#include <unistd.h>
#include <stdio.h>

int main(void)
{
int idx;
char *argv[][4] = { {"/bin/sh", "-c", "echo Hello 1", 0},
{"/bin/sh", "-c", "echo Hello 2", 0},
{"/bin/sh", "-c", "echo Hello 3", 0} };
for (idx = 0; idx < 3; idx++)
{
if (0 == fork()) continue;
execve(argv[idx][0], &argv[idx][0], NULL);
fprintf(stderr, "Oops!\n");
}

return 0;
}

使用命令连接的方法:
解决方法是使用 shell 连接命令:

输出:

Hello 1
Hello 2

代码:

#include <unistd.h>
#include <stdio.h>

int main(void)
{
char *argv[] = {"/bin/sh", "-c", "echo Hello 1 && echo Hello 2", 0};
execve(argv[0], &argv[0], NULL);
fprintf(stderr, "Oops!\n");

return 0;
}

关于c - 执行 : how can I initialise char *argv[ ] with multiple commands instead of a single command?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com