Linux execve() 有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10068327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does execve() do?
提问by Nosrettap
What exactly does execve() do? I've tried looking at the documentation (http://linux.die.net/man/2/execve) but given that I'm very new to linux and this sort of programming it doesn't make a lot of sense. What I want to do is be able to execute this command:
execve() 到底做了什么?我试过查看文档(http://linux.die.net/man/2/execve),但鉴于我对 linux 很陌生,而且这种编程没有多大意义。我想要做的是能够执行这个命令:
nc -l -p someport -e /bin/sh
Can I do something like the following (where someport is a number such as 4444)
我可以执行以下操作吗(其中 someport 是一个数字,例如 4444)
char *command[2];
command[0] = "nc -l -p someport -e /bin/sh"
execve(command[0], name, NULL);
采纳答案by geekosaur
Correct usage is
正确的用法是
extern char * const environ[];
char * const command[] = {"nc", "-l", "-p", "porthere", "-e", "/bin/sh", NULL};
execve("/usr/bin/nc", command, environ);
You must use a full pathname, not a short name such as "nc"
(more precisely: no PATH
search is done, the pathname must be an actual existing file), and you must split arguments into separate strings beforehand. You also need to propagate the environment somehow, either via the extern environ
mentioned in the above snippet or as obtained from the third parameter of main()
; the latter is slightly more standards-blessed but may be more painful to pass around as needed.
您必须使用完整的路径名,而不是短名称,例如"nc"
(更准确地说:不进行PATH
搜索,路径名必须是实际存在的文件),并且您必须事先将参数拆分为单独的字符串。您还需要以某种方式传播环境,通过environ
上面代码片段中提到的 extern或从main()
;的第三个参数获得。后者稍微更符合标准,但根据需要传递可能会更痛苦。
回答by Jerry Coffin
execve
replaces the current process with a new process, running the command you specified as its first argument.
execve
用新进程替换当前进程,运行您指定为其第一个参数的命令。
Chances are pretty decent that you want execvp
or execlp
instead -- you haven't mentioned anything about wanting to provide the environment for the child, but from the looks of things you probably do want the path searched to find the executable you're using.
您想要execvp
或execlp
相反的机会相当不错——您没有提到想要为孩子提供环境的任何内容,但从事情的角度来看,您可能确实希望搜索路径以找到您正在使用的可执行文件。