如何execvp运行命令? [英] How does execvp run a command?

查看:151
本文介绍了如何execvp运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 execvp 可用于执行简单的命令如下:

I know execvp can be used to execute simple commands as follows:

char* arg[] = {"ls", "-l", NULL};
execvp(arg[0],arg);

我想知道这里的​​推移,当我运行 execvp 。在手册页它说 execvp 替换为新的一个过程图像的图像。但是在这里,我运行一个命令不是可执行。

I want to know what goes on in here when I run execvp. In man page it says execvp replaces the image of the process image with the new one. However here I am running a command not an executable.

要具体而言,说有特异性需要输入例如一个命令猫。如果我有一个包含预期的猫文件名的文本文件的text.txt和我标准输入重定向到文件的文件流,将 execle(猫,猫,输出NULL ) execvp(猫,ARG)(显然其中arg商店 NULL )的结果在控制台输出为猫/文件名会吗?我的直觉是我要读文件,并且可以解析它的参数存储在ARG。不过,我想确认一下。

To be specific, say there is a command that specifically requires an input e.g. cat. If I have a text file text.txt which contains the file name expected for cat and I redirect stdin to the file stream of the file, would the output of execle("cat","cat",NULL) or execvp("cat", arg) (obviously where arg stores "cat" and NULL) result in the output in the console as the cat /filename would? My intuition is I have to read the file and may be parse it to store the arguments in the arg. However I want to make sure.

在此先感谢!

推荐答案

下面是在 execvp 通话会发生什么:

Here's what happens in an execvp call:


  1. PATH你的libc实现搜索,如果适用,因为这是要执行的文件。大多数情况下,如果不是全部,在命令中的类UNIX系统的可执行文件。如果不是,会发生什么?尝试一下。看一看<一个href=\"http://sourceware.org/git/?p=glibc.git;a=blob;f=posix/execvpe.c;h=588e7a71b1a5b507c7628b4ec7a467f4ba78b1d3;hb=HEAD\">how glibc的做它。

  2. 通常,如果可执行文件被发现,到的execve A的通话将被制成。 的execve 的某些部分可能在libc中来实现,也可以是(在Linux下等)系统调用。

  3. Linux的prepares通过为它分配内存,打开它,安排其执行,初始化内存结构的程序,从提供的参数来 execvp 电话,找到适合装载二进制处理程序,并将当前任务( execvp 调用者)不执行。你可以在这里找到其执行

  1. Your libc implementation searches in PATH, if applicable, for the file that is to be executed. Most, if not all, commands in UNIX-like systems are executables. What will happen if it is not? Try it. Have a look at how glibc does it.
  2. Typically, if the executable is found, a call to execve will be made. Parts of execve may be implemented in libc or it may be a system call (like in Linux).
  3. Linux prepares a program by allocating memory for it, opening it, scheduling it for execution, initialises memory structures, sets up its arguments and environment from the supplied arguments to the execvp call, finds a handler appropriate for loading the binary, and sets the current task (the execvp caller) as not executing. You can find its implementation here.

以上所有步骤符合由POSIX的要求其在相关手册页的描述。

All steps above conform to the requirements set by POSIX which are described in the relevant manual pages.

这篇关于如何execvp运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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