How does execvp run a command?

后端 未结 4 1223
温柔的废话
温柔的废话 2020-12-23 21:54

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

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

I w

4条回答
  •  星月不相逢
    2020-12-23 22:46

    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.

提交回复
热议问题