Linux process 5: Summary of exec family functions (execl, execlp, execle, execv, execvp, execvpe) and the use of exec with fork

exec family functions (execl, execlp, execle, execv, execvp, execvpe) and exec are used with fork

The role of exec family functions:

After we create a new process with the fork function, we often call the exec function in the new process to execute another program.When the process calls the exec function, the process is completely replaced with a new program. Because calling the exec function does not create a new process, So the ID of the process before and after has not changed.

Features:

Execute an executable file inside the calling process. The executable file can be a binary file or any script file executable under Linux

Function family:

The exec function families are: execl, execlp, execle, execv, execvp, execvpe

Function prototype:

#include <unistd.h>
extern char **environ;

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 execvpe(const char *file, char *const argv[],char *const envp[]);

return value:

The functions of the exec function family will not return after successful execution. When the call fails, errno will be set and -1 will be returned, and then continue from the call point of the original program.

Parameter Description:

path: the path name of the executable file
arg: the parameters of the executable program,The first parameter is the name of the executable file, without a path and arg must end with NULL
file: If the parameter file contains /, it will be treated as a path name, otherwise, it will search for executable files in the directories specified by the PATH environment variable.
exec family function parameters are extremely difficult to remember and distinguish, the characters in the function name will give us some help:
l: use the parameter list
p: use the file name, and search for the executable file from the PATH environment
v: first construct a pointer to each parameter Array of pointers, and then the address of the array as the parameter of these functions.
e: Add the envp[] array, use new environment variables instead of the environment variables of the calling process

The exac function is classified into four categories with l, p, v, and e to illustrate the characteristics of the parameters.

1. A type of exac function with l (l stands for list), including execl, execlp, execle, and requires that each command line parameter of the new program be described as a separate parameter. This parameter list ends with a null pointer.

Take the execl function as an example to illustrate:

Case demonstration: The process calls the execl function to execute the echoarg.c program.
The execl function needs to execute another program:

//文件echoarg.c
#include <stdio.h>
int main(int argc,char *argv[])
{
    
    
    int i = 0;
    for(i = 0; i < argc; i++)
    {
    
    
        printf("argv[%d]: %s\n",i,argv[i]); 
    }
    return 0;
}

operation result:
Insert picture description here

execl function code:

//文件demo3.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
    
    
    printf("before execl\n");
    if(execl("./echoarg","echoarg","abc",NULL) == -1)
    {
    
    
        printf("execl failed!\n");      
    }
    printf("after execl\n");
    return 0;
}

operation result:
Insert picture description here
Experiment description:
We first compile echoarg.c with gcc to generate the executable file echoarg (and put it in the current path (.bin or ./) directory). The function of file echoarg is to print command line parameters. Then compile execl.c and execute the execl executable file. Use execl to find and execute echoarg, replace the current process main, so "after execl" is not printed out in the terminal.
Supplement 1:

whereis ls:打印ls的绝对路径

Insert picture description here

if(execl("/bin/ls","ls",NULL,NULL) == -1)
//修改后打印当前路径所有文件
if(execl("/bin/ls","ls",-l”,NULL) == -1)
//以列表形式显示

Supplement 2:

whereis date:获取系统的时间的路径

Insert picture description here

 if(execl("/bin/date","date",NULL,NULL) == -1)
 //改写后,获取系统时间

Supplement 3:

whereis ps: 获取系统进程ID路径

Insert picture description here

if(execl("/bin/ps","ps",NULL,NULL) == -1)
 //改写后,获取系统进程ID

Don't know the absolute pathIn the case of display not found (for example, only know ps):
use:

execlp if(execl("ps","ps",NULL,NULL) == -1)

2. A type of exac function with p, including execlp, execvp, execvpe, if the parameter file contains /, it will be regarded as the path name, otherwise it will be searched in the directories specified by the PATH environment variable. executable file.
For example:
PATH=/bin:/usr/bin

The directory specified by the current environment variable:

//环境变量作用:查找需要的可执行文件
echo $PATH  //当前环境变量
pwd  //当前路径
export PATH=$PATH:/home/dazai //当前环境变量所在的当前路径
echo $PATH   //当前环境变量
ls   //显示文件

Green can be executed:
Insert picture description here

The exaclp function above has p, so the executable file ps can be found through the environment variable PATH

First look at the exacl function code demonstration:

//文件execl_no_path.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
    
    
    printf("before execl****\n");
    if(execl("ps","ps","-l",NULL) == -1)
    {
    
    
        printf("execl failed!\n");
    }   
    printf("after execl*****\n");
    return 0;
}

Operation result: In the
Insert picture description here
above example, because the parameter does not have a path, execl cannot find the executable file.
Let's look at another example for comparison:

//文件execlp.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execlp(const char *file, const char *arg, ...);
int main(void)
{
    
    
    printf("before execlp****\n");
    if(execlp("ps","ps","-l",NULL) == -1)
    {
    
    
        printf("execlp failed!\n");
    }
    printf("after execlp*****\n");
    return 0;
}

Running results:
Insert picture description here
As can be seen from the above experimental results, the exaclp function above has p, so the executable file ps can be found through the environment variable PATH.

3. A type of exac function with v without l, including execv, execvp, execve, should first construct an array of pointers to each parameter, and then use the address of the array as the parameter of these functions.

For example:
such as char *arg[], and the last element of arg must be NULL

char *arg[] = {
    
    “ls”,-l”,NULL}; 

BelowexecvpFunction as an example:

//文件execvp.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execvp(const char *file, char *const argv[]);
int main(void)
{
    
    
    printf("before execlp****\n");
    char *argv[] = {
    
    "ps","-l",NULL};
    if(execvp("ps",argv) == -1) 
    {
    
    
        printf("execvp failed!\n");     
    }
    printf("after execlp*****\n");
    return 0;
}

operation result:
Insert picture description here
4. A type of exac function with e, including execle and execvpe, can pass a pointer to the environment string pointer array.
Parameters such as:

char *env_init[] = {
    
    “AA=aa”,”BB=bb”,NULL}; 

With e means that the function takes the envp[] array instead of using the current environment.

BelowexecleFunction as an example:

//文件execle.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execle(const char *path, const char *arg,..., char * const envp[]);
char *env_init[] = {
    
    "AA=aa","BB=bb",NULL};
int main(void)
{
    
    
    printf("before execle****\n");
        if(execle("./echoenv","echoenv",NULL,env_init) == -1)
        {
    
    
                printf("execle failed!\n");
        }       
    printf("after execle*****\n");
    return 0;
}

Test code:

//文件echoenv.c
#include <stdio.h>
#include <unistd.h>
extern char** environ;
int main(int argc , char *argv[])
{
    
    
    int i;
    char **ptr;
    for(ptr = environ;*ptr != 0; ptr++)
        printf("%s\n",*ptr);
    return 0;
}

Test result:
Insert picture description here
We first write a program that displays all the environment tables, name it echoenv.c, and then compile it into an executable file and place it in the (./bin or ./) directory. Then run the executable file execle and found that the environment variables we set are indeed passed in.

5. exec is used with fork:

Realization function:
When the parent process detects that the input is 1, create a child process to change the field value of the configuration file.

Reference Code:

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
    
    
 pid_t pid;
 int data=10;
 while(1)
 {
    
    
  printf("请输入数据:\n");
  scanf("%d",&data);
  if(data == 1)
  {
    
    
   pid=fork();
   if(pid>0)
   {
    
    
    wait(NULL);//防止变成僵尸进程
   }
   if(pid==0)
   {
    
    
    execl("./changdata","changdata","config.txt",NULL);//执行别的   
   }
  }
  else
  {
    
    
   printf("神码也不做\n");
  }
 }
 return 0;
}

Guess you like

Origin blog.csdn.net/weixin_40734514/article/details/108993029