Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does execvp run a command?

Tags:

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

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

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.

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.

Thanks in advance!

like image 711
as3rdaccount Avatar asked Jan 13 '13 07:01

as3rdaccount


People also ask

What does the Execvp () command do?

The execvp function is most commonly used to overlay a process image that has been created by a call to the fork function. identifies the location of the new process image within the hierarchical file system (HFS).

Is Execvp a system call?

execvp : Using this command, the created child process does not have to run the same program as the parent process does. The exec type system calls allow a process to run any program files, which include a binary executable or a shell script .

Does Execvp call exit?

execvp will not return (unless pArgs[0] is not a valid executable file), so the exit(0) statement will never be reached. "unless pArgs[0] is not a valid executable file" - there are a myriad of reasons why exec* may fail, that being only one. Permissions, resource counts, memory - errno will tell you.


1 Answers

Here's what happens in an execvp call:

  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.

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

like image 84
Michael Foukarakis Avatar answered Oct 13 '22 20:10

Michael Foukarakis