Exec replacement process impression, exec Replacement Process
Overview
On Process Creation, UNIX/Linux adopts a unique method, which separates Process Creation from loading a new process image (system calls combine these two operations ). The advantage is that there is more room to manage the two operations.
After we create a process, we usually replace the child process with a new process image. This can be done using exec functions. Of course, the exec series functions can also replace the current process (do not call fork, directly call exec ).
Function Family [map page] Information
# Include <unistd. h> extern char ** environ; int execl (const char * path, const char * arg ,...); // L: command list int execlp (const char * file, const char * arg ,...); // p: execle int (const char * PATH, const char * arg ,..., char * const envp []); int execv (const char * path, char * const argv []); int execvp (const char * file, char * const argv []); int execvpe (const char * file, char * const argv [], char * const envp []); int execve (const char * filename, char * const argv [], char * const envp []);
Note:
The number of parameters for execl, execlp, and execle (all with "l") is variable. The parameter must end with a null pointer.
The second parameter of execv and execvp is a string array ("v" represents "vector", and the string array must end with NULL ), when the new program starts, it will pass the given parameters in the argv array to main.
The function with the last letter "p" will search for the PATH environment variable to find the executable file of the new program. If the executable file is not in the PATH defined by PATH, you must pass the absolute file name including the subdirectory as a parameter to these functions.
/* Conclusion: l represents the variable parameter list, and p represents searching the file in the path environment variable. Envp represents the environment variable */
Example execlp
#include <unistd.h>#include <iostream>using namespace std;int main(){ execlp("/bin/pwd","/bin/pwd",NULL); //execlp("ls","ls","-l",NULL); cout << "After fork..." << endl; return 0;}
Example execve
int main(){ char *const args[] = { (char *)"/bin/date", (char *)"+%F", NULL }; execve("/bin/date",args,NULL); cout << "After fork..." << endl; return 0;}
Example execle
// Main. cpp # include <unistd. h ># include <iostream> using namespace std; int main () {cout <"In main, pid =" <getpid () <endl; char * const environ [] = {"AA = 11", "BB = 22", "CC = 33", NULL}; execle (". /hello ",". /hello ", NULL, environ); // when environ is NULL, no cout is passed. <" After fork... "<endl; return 0;} // hello. cpp # include <unistd. h> # include <iostream> using namespace std; extern char ** environ; int main (){ Cout <"In hello, pid =" <getpid () <endl; cout <"environ:" <endl; for (int I = 0; environ [I]! = NULL; ++ I) {cout <"\ t" <environ [I] <endl ;}}
/* In main, pid = 3572 // PID remains unchanged In hello, pid = 3572 environ: AA = 11BB = 22CC = 33 */