Linux Process thread learning notes: Run New Programs

Source: Internet
Author: User

Linux Process thread learning notes: running newProgram

Zhou yinhui

 

As we mentioned in the previous article, when a new process is started, the new process will copy most of the context of the parent process and then runCodeIf we make the new process not run the code of the original parent process, and then run the code in another assembly, this is equivalent to starting a new program. The code here can be understood as an executable program.

Therefore, to run a new program, two basic steps are required:

1. Create an environment for running programs, that is, processes.

2. Replace the content in the environment with what you want, that is, overwrite the original image in the new process with the executable file you want to run, the execution starts from the beginning of the executable file.

To achieve the first point, it is very simple. You can use the fork function (refer to the previous article). To achieve the second point, you can use the exec function family.

 

Exec is short for a family of functions, including <unistd. h>.

The prototype is as follows:

Int execl (const char *Path, Const char *Arg0,.../*, (Char *) 0 */); 

Int execlp (const char *File, Const char *Arg0,.../*, (Char *) 0 */); 


Int execle (const char *Path, Const char *Arg0,.../*, (Char *) 0, char * constEnvp[] */); 

Int execv (const char *Path, Char * const Argv[]); 

Int execvp (const char *File, Char * constArgv[]);


Int execve (const char *Path, Char * const Argv[], Char * const Envp[]);

Let's take the simplest execl function as an example. The others are similar. The first parameter path is the path of the executable file, which is the absolute path; starting from the arg0 parameter and all the following command line parameters that you want to pass to the executable file, it is worth noting that, arg0 is the executable file itself (Do you still remember what the teacher said when talking about the main function parameter list in C), of course, if the program itself is not passed or some messy values are passed, it does not mean that the program cannot be compiled or run. However, if the executable file needs to use arg0, it will lead to some confusion; there is a comment/*, (char *) 0 */which reminds us that the last parameter should be a null string. If a function runs successfully, no return value is returned. Otherwise,-1 is returned. The specific error code is set in errno. errno is a global variable used to set the error code, similar to the getlasterror function of Win32.

See the following example:

# Include < Stdio. h >
# Include < Unistd. h >

IntMain ()
{
Printf ("APP start... \ n");

Execl ("/Bin/ls","/Bin/ls","-L", Null );

Printf ("APP end \ n");

Return 0;
}

We run the LS program in the bin directory. When arg0 is used, the path of the LS program is-L, so that arg1 can list the current directory as a list, the program output on my computer is as follows:

APP start...
Total 12
-RW-r -- 1 Zhouyh 273   2010 - 09 - 06   11 : 09 Temp. c
-Rwxr-XR-x 1 Zhouyh 7175   2010 - 09 - 06   11 : 09 Temp.exe

The ls program is successfully run. But have you noticed? There is no output of the "app end" string. The reason is simple. Instead of starting a new process, we directly overwrite the process where the main function is located with the LS program.

Next, use fork to avoid affecting the original process.

 

# Include < Stdio. h >
# Include < Unistd. h >

int main ()
{< br> printf ( " app start... \ n " );
If (Fork () = 0 )
{< br> execl ( " /bin/ls " , " /bin/ls " , " -L " , null );
}< br>
printf ( " app end \ n " );
return 0 ;
}

We used fork to create a new process. After it is successfully created (the return value is 0), we used execl to load the LS program and run it.

The program output is as follows:

APP start...
APP end
Zhouyh @ Ubuntu :~ /Documents $ total 12
-RW-r -- 1 Zhouyh 229   2010 - 09 - 06   15 : 59 Temp. c
-Rwxr-XR-x 1 Zhouyh 7211   2010 - 09 - 06   16 : 00 Temp.exe

 

All the output of the program is OK, but one thing that may be different from what we think is that the "app end" string has been output very early rather than at the end. In fact, there is nothing wrong with it, "app end" is output when the program (temp.exe) of the mainprogram is about to end, while the LS listing the file directory is completely in another process, two asynchronous processes, no one of them should start and end.

 

If we want to output "app end" after all the work is completed, that is, after LS is executed and played, we can use the wait and waitpid functions. Here we will briefly describe wait, for details, refer to "Linux Process thread learning notes: Process Control.
Pid_t wait (int * status); // contained in <sys/Wait. H>

The wait function indicates that the current process is sleep until a sub-process of the process ends or a specific signal is sent to wake up. If the child process ends normally, the child process ID (PID) is used as the return value. If an error occurs,-1 is returned, and the status parameter indicates the end status of the child process.
For the example above, refer to the following code:

# Include < Stdio. h > // For printf (const char)
# Include < Unistd. h > // For fork ()
# Include < Sys / Wait. H >   // For wait (int * Status)

Int Main ()
{
Printf ( " APP start... \ n " );

If (Fork () =   0 )
{
Execl ( " /Bin/ls " , " /Bin/ls " , " -L " , Null );
}

Int Status;
Wait ( & Status );

Printf ( " APP end \ n " );

Return   0 ;
}

 

The program output is as follows:

APP start...
Total 12
-RW-r -- 1 Zhouyh 337   2010 - 09 - 06   16 : 22 Temp. c
-Rwxr-XR-x 1 Zhouyh 7247   2010 - 09 - 06   16 : 22 Temp.exe
APP end

 

Now let's look at the other functions except execl:

 

Int execlp (const char *File, Const char *Arg0,.../*, (Char *) 0 */);

Execlp is similar to execl, but the difference is that the former will go to the system environment variable to find the location of the program referred to by file, so if you can find the executable file through the environment variable, the file may not be an absolute path, such as execlp ("ls", "ls", "-l", null );

 

Int execle (const char *Path, Const char *Arg0,.../*, (Char *) 0, char * constEnvp[] */); 

Unlike execlp, the last parameter is passed in as your custom environment variable parameter, rather than searching for system environment variables.

Char* Env [] = {"Home =/usr/home","LOGNAME = home",(Char*)0};

Execle("/Bin/ls","Ls","-L",Null, ENV );

 

Int execv (const char *Path, Char * const Argv[]); 

Int execvp (const char *File, Char * constArgv[]);

Int execve (const char *Path, Char * const Argv[], Char * const Envp[]);

These three functions are similar to the preceding three functions. The function name is changed from the suffix L to v. The meaning of the function is that the parameter is not transmitted using the parameter list, but is transmitted using a parameter array argv []. of course, the last element of the array must also be char * 0

 

Functions with similar names are easy to confuse, so let's differentiate them from extensions such as l, V, p, and E:
L: a list of parameters separated by commas (,), ending with char * 0.

V: The parameter is a string array. The last element of the array is char * 0.

P: You can use the system environment variable to find the file location.

E: The caller displays the input environment variables.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.