Exec function family for Linux Process Control Programming

Source: Internet
Author: User

I wanted to write a small article recording the exec function family myself, but when I learned the relevant knowledge, I found that the previous article on the Internet has been quite detailed. So we use another stone. The following is an excerpt from http://www.ibm.com/?works/cn/linux/kernel/syscall/part3/index.htmland stored in the exec family.

 

 

1.10 Exec

Some readers may have read this series of articles from the very beginning, but there is still a big question: Since all new processes are generated by fork, in addition, the sub-processes generated by fork are almost identical with the parent process. Doesn't that mean that all the processes in the system should be identical? Moreover, in our common sense, when we execute a program, the content of the new process should be the content of the program. Did we get it wrong? Obviously not. To solve these questions, we must mention the exec system call that we will introduce below.

1.10.1 Introduction

It is called by the exec system. In fact, in Linux, there is no exec () function form. Exec refers to a group of functions, with a total of six functions:

#include <unistd.h>int execl(const char *path, const char *arg, ...);int execlp(const char *file, const char *arg, ...);int execle(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 execve(const char *path, char *const argv[], char *const envp[]);

Among them, only execve is a real system call, and others are packaged library functions on this basis.

The exec function family finds an executable file based on the specified file name and uses it to replace the content of the calling process. In other words, it executes an executable file within the calling process. The executable file can be either a binary file or any script file that can be executed in Linux.

Unlike in general, functions in the exec function family are not returned after successful execution, because the entity of the calling process, including the code segment, data segment, and stack, has been replaced by new content, only some superficial information such as the process id remains unchanged, which is quite similar to the "golden shell" in the "Plan ". It looks like an old shell, but it has injected a new soul. Only when the call fails will they return a-1, which will be executed from the original program's call point.

Now we should understand how a new program is executed in Linux. Every time a process thinks that it cannot make any contribution to the system and support, it can make full use of the last point, call any exec to regenerate itself with a new look; or, more commonly, if a process wants to execute another program, it can fork a new process, then call any exec, which looks like a new process is generated by executing the application.

In fact, the second scenario is so widely used that Linux has made special optimizations for it. We already know that, fork will copy all the content of the calling process to the newly generated child process, which consumes a lot of time. If fork is finished, we will call exec immediately, these hard-to-copy items will be immediately erased, which seems very uneconomical, so people have designed a technology called "Copy-on-write, so that the fork does not copy the content of the parent process immediately after the end, but is copied only when the fork is actually practical, so that if the next statement is exec, it will not be useless, this improves efficiency.

1.10.2 a little deeper

The above six functions seem very complex, but in fact they are very similar in both functions and usage, with only a small difference. Before learning about them, let's take a look at the common main function.

The form of the main function below may be somewhat unexpected:

int main(int argc, char *argv[], char *envp[])

It may be different from what is described in most textbooks, but in fact, this is the real complete form of the main function.

The argc parameter specifies the number of command line parameters when the program is run. The array argv stores all command line parameters, and the array envp stores all environment variables. Environment Variables refer to a set of values that have existed since user login. Many applications need to rely on them to determine system details. Our most common environment variables are path, it points out where to search for applications, such as/bin; home is also a common environment variable, it points out our personal directory in the system. Environment variables generally exist as strings "xxx = xxx". xxx indicates the variable name, and XXX indicates the variable value.

It is worth mentioning that the argv array and the envp array both store pointer to the string. Both arrays end with a null element.

We can use the following program to view what is uploaded to argc, argv, and envp:

/* main.c */int main(int argc, char *argv[], char *envp[]){printf("/n### ARGC ###/n%d/n", argc);printf("/n### ARGV ###/n");while(*argv)printf("%s/n", *(argv++));printf("/n### ENVP ###/n");while(*envp)printf("%s/n", *(envp++));return 0;}

Compile it:

$ cc main.c -o main

When running, we intentionally add a few command line parameters that do not have any function:

$ ./main -xx 000### ARGC ###3### ARGV ###./main-xx000### ENVP ###PWD=/home/leiREMOTEHOST=dt.laser.comHOSTNAME=localhost.localdomainQTDIR=/usr/lib/qt-2.3.1LESSOPEN=|/usr/bin/lesspipe.sh %sKDEDIR=/usrUSER=leiLS_COLORS=MACHTYPE=i386-redhat-linux-gnuMAIL=/var/spool/mail/leiINPUTRC=/etc/inputrcLANG=en_USLOGNAME=leiSHLVL=1SHELL=/bin/bashHOSTTYPE=i386OSTYPE=linux-gnuHISTSIZE=1000TERM=ansiHOME=/home/leiPATH=/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/lei/bin_=./main

We can see that the program uses "./main" as 1st command line parameters, so we have three command line parameters. This may be a little different from what you usually get used to. Be careful not to make a mistake.

Now let's look at the exec function family and focus on execve:

int execve(const char *path, char *const argv[], char *const envp[]);

Compare the complete form of the main function. Do you see the problem? Yes, the argv and envp in these two functions have a one-to-one relationship. The execve 1st parameter path is the complete path of the application to be executed, and the 2nd parameter argv is the command line parameter passed to the application to be executed, the 3rd envp parameter is the environment variable passed to the application to be executed.

Take a look at these six functions and you can find that the first three functions start with execl, and the last three functions start with execv. The difference between them is that, the functions starting with execv pass the command line parameters in the form of "char * argv []", while the functions starting with execl use a method that we prefer to list parameters one by one, end with a null expression. Here, the role of null is the same as that of null in the argv array.

Of all six functions, only execle and execve use char * envp [] to pass environment variables. None of the other four functions have this parameter, this does not mean that they do not pass environment variables. These four functions will pass the default environment variables to the executed applications without any modification. Execle and execve Replace the default ones with the specified environment variables.

There are two other functions execlp and execvp ending with P. It seems that they have very little difference with execl and execv, and that is true, too, all four functions except execlp and execvp require that their 1st parameter paths must be a complete path, such as "/bin/ls "; the 1st file parameters of execlp and execvp can be simply a file name, such as "ls". These two functions can be automatically searched in the directory specified by the Environment Variable path.

1.10.3 practice

The knowledge is almost introduced. Next let's look at the actual application:

/* exec.c */#include <unistd.h>main(){char *envp[]={"PATH=/tmp","USER=lei","STATUS=testing",NULL};char *argv_execv[]={"echo", "excuted by execv",NULL};char *argv_execvp[]={"echo", "executed by execvp", NULL};char *argv_execve[]={"env", NULL};if(fork()==0)if(execl("/bin/echo", "echo", "executed by execl", NULL)<0)perror("Err on execl");if(fork()==0)if(execlp("echo", "echo", "executed by execlp", NULL)<0)perror("Err on execlp");if(fork()==0)if(execle("/usr/bin/env", "env", NULL, envp)<0)perror("Err on execle");if(fork()==0)if(execv("/bin/echo", argv_execv)<0)perror("Err on execv");if(fork()==0)if(execvp("echo", argv_execvp)<0)perror("Err on execvp");if(fork()==0)if(execve("/usr/bin/env", argv_execve, envp)<0)perror("Err on execve");}

The program calls two common Linux system commands, ECHO and Env. Echo will print out the command line parameters that follow, and env will be used to list all environment variables.

As the execution sequence of each sub-process cannot be controlled, a chaotic output may occur-the printed results of each sub-process are mixed together, rather than strictly following the order listed in the program.

Compile and run:

$ cc exec.c -o exec$ ./execexecuted by execlPATH=/tmpUSER=leiSTATUS=testingexecuted by execlpexcuted by execvexecuted by execvpPATH=/tmpUSER=leiSTATUS=testing

As expected, the result of execle output goes to the front of execlp.

In normal programming, if you use the exec function family, you must add an incorrect judgment statement. Compared with other system calls, exec is prone to injury, and the execution file location, permissions, and many other factors can cause the call to fail. The most common errors are:

  1. The file or path cannot be found, and errno is set to enoent;
  2. Array argv and envp forget to end with null. errno is set to efault;
  3. You are not authorized to run the file to be executed. errno is set to eacces.

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.