Exec provides a method to start the execution of another program in the process. It can locate the executable file based on the specified file name or directory name and use it to replace the data segment, code segment, and stack segment of the original calling process. After execution, all the content of the original called process except the process number is replaced.
1. Executable File Search Method
The function ending with P in the exec family can only provide the file name. The system automatically searches for the path contained in the environment variable "$ path.
That is, if the end is not P, the file path must be given and the final parameter is null;
2. parameter table Transmission Method
Two Methods: list all parameters one by one or pass them through a pointer array.
It is distinguished by the fifth letter of the function name. If the letter is "L" (list), it indicates listing one by one;
The letter "V" (vertor) indicates that all parameters are constructed as pointer Arrays for transmission;
3. Use of Environment Variables
The exec function family can use the system environment variables by default, or pass in the specified environment variables. Here, the two functions ending with "E" (Environment) can pass the environment variables used by the current process in envp.
Exec (1, 2, 3..., last parameter)
In the exec family, the first parameter is the path of the program to be executed.
The second parameter is the name of the program to be executed.
The third parameter is to pass parameters to the program to be executed.
The last parameter is null;
Example:
Int main ()
{
If (-1 = execle ("./exec2", "exec2", "1.txt", null ))
{
Perror ("");
Exit (0 );
}
} // Open the exec2 executable file and pass "1.txt" to the parameter in the main function of exec2
Exit () call to exit the processing function, clear the cache, call the exit system call, and the process ends.
_ Exit () does not clear the cache.
Shell imitation using Exec:
# Include <stdio. h>
# Include <sys/Wait. H>
# Include <sys/STAT. h>
# Include <stdlib. h>
# Include <errno. h>
# Include <string. h>
# Include <unistd. h>
# Define n 64
Int main ()
{
Pid_t PID;
Char Buf [N];
Char * Arg [N];
Int I = 0;
Printf ("> ");
While (fgets (BUF, N, stdin )! = NULL)
{
Buf [strlen (BUF)-1] = 0;
If (pid = fork () =-1)
{
Perror ("fork ");
Exit (-1 );
}
If (pid = 0)
{
Arg [I ++] = strtok (BUF ,"");
Do
{
Arg [I ++] = strtok (null ,"");
} While (ARG [I-1]! = NULL );
If (execvp (ARG [0], ARG )! =-1)
{
Perror ("execvp ");
Exit (0 );
}
}
Else
{
Wait (null );
Printf ("> ");
}
}
Exit (0 );
}