Ç - 执行命令猛砸与Execvp [英] C - Executing Bash Commands with Execvp

查看:190
本文介绍了Ç - 执行命令猛砸与Execvp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个接受输入的文本文件,其中包含由换行符separeted的bash命令,并在文本文件中执行每一个命令的程序壳牌codeC:例如,文本文件将包含:

I want to write a program Shellcode.c that accepts in input a text file, which contains bash commands separeted by newline, and executes every commands in the text file: for example, the text file will contain:

echo Hello World
mkdir goofy   
ls

我想这一个(刚开始用的Exec功能之一执业):

I tried this one (just to begin practicing with one of the exec functions):

#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);
}

我得到的,作为回报,

I get, in return,

echo: Can't open Hello World

我坚持用execvp的功能,我有没有去哪里错了?

I'm stuck with the execvp function, where did I go wrong?

推荐答案

您就错了。

第一个数组索引是程序的名称,如在文档解释说:

The first array index is the name of the program, as explained in the docs:

在execv(),execvp()和execvpe()函数提供的指针数组以空值终止的重新present提供给新程序的参数列表的字符串。第一个参数,按照惯例,应该指向与正在执行的文件相关联的文件名。指针数组必须由一个NULL指针被终止。

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.

此外,庆典并不指望自由形式的说法那样,你需要告诉它你要通过使用 -c 选项命令:

Also, bash doesn't expect free-form argument like that, you need to tell it you're going to pass commands using the -c option:

所以,你需要:

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

这篇关于Ç - 执行命令猛砸与Execvp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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