C - 使用 Execvp 执行 Bash 命令

标签 c bash execvp

我想编写一个程序 Shellcode.c,它接受输入文本文件,其中包含由换行符分隔的 bash 命令,并执行文本文件中的每个命令:例如,文本文件将包含:

echo Hello World
mkdir goofy   
ls

我尝试了这个(只是为了开始练习其中一个 exec 函数):

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

void main() {
    char *name[3];

    name[0] = "echo";
    name[1] = "Hello World";
    name[2] = NULL;
    execvp("/bin/sh", name);
}

我得到,作为返回,

echo: Can't open Hello World

我被 execvp 函数卡住了,我哪里出错了?

最佳答案

你做错了。

第一个数组索引是程序的名称,如explained in the docs :

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.

此外,bash 不期望这样的自由格式参数,您需要告诉它您将使用 -c 选项传递命令:

所以,你需要:

name[0] = "sh";
name[1] = "-c";
name[2] = "echo hello world";
name[3] = NULL;

关于C - 使用 Execvp 执行 Bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14141007/

相关文章:

c - 选择返回 "No such file or directory"

bash - 导出路径不保存

bash - 在 awk 中运行外部命令

c - exec、execvp、execl、execv 之间的区别?

c - avformat_write_header 失败并出现错误“无效参数

c - C代码的优化

c++ - 涉及将 vector 转换为 feed 到 execvp 的错误类型

c - 在 main 中等待 execvp

c++ - 自定义 CMake 配置类型。我能以某种方式从调试中得到 "inherit"吗?

html - 使用 bash,最好是 sed,命令删除 markdown (md) 文件中的图像和链接标签