Trying to understand how execvp works

ぐ巨炮叔叔 提交于 2019-12-02 07:39:52

The prototype is:

  int execvp(const char *file, char *const argv[]);

The first argument, file is the name of the program to execute. execvp will search your path and try to find a match. From the manpage:

The execlp(), execvp(), and execvpe() functions duplicate the actions of the shell in searching for an executable file if the specified file name does not contain a slash (/) character.
The file is sought in the colon-separated list of directory pathnames specified in the PATH environment variable.

If/when execvp finds a match, that program will be loaded into memory and replace your current running program.

The arguments the new program will see are the argv array specified in execvp. You are expected to have a null pointer as the last element, or your program may crash looking for a null.

If you do:

char *argv[]={"bar","bash","penguin",0};
execvp("foo",argv);

then when foo starts, it will have the same environment as your current program, its argc will be 3 and its argv will be the above list. Even though the program name is "foo", it's argv[0] while running will show up as "bar".

You don't actually have to have argv[0] be the name of the new program. It is expected, but not required.

Incidentally, with your example of

ls > awd.txt

If you did this on the command line, your shell would fork creating a new copy of itself. The child shell would open awd.txt and do a dup2() to put the child fd attached to awd.txt as 1. After some other housekeeping, the child shell would do something like.

execvp("ls", {"ls", 0})

so in the created "ls" argc==1 and argv[1] ==0. Traditionally , we would say that ls has 0 arguments.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!