• exec函数族


    进程程序替换

    • 进程程序替换原理

    fork创建子进程执行的是和父进程相同的程序(也有可能是某个分支),通常fork出的子进程是为了完成父进程所分配的任务,所以子进程通常会调用一种exec函数(六种中的任何一种)来执行另一个任务。当进程调用exec函数时,当前用户空间的代码和数据会被新程序所替换,该进程就会从新程序的启动历程开始执行。在这个过程中没有创建新进程,所以调用exec并没有改变进程的id。

    • 替换图解(图解)

    exec函数族

    1. 执行指定目录下的程序

    int execl(const char *path, const char *arg, ...);

    分析:

    • path: 要执行的程序的绝对路径
    • 变参arg: 要执行的程序的需要的参数
    • 第一arg:占位
    • 后边的arg: 命令的参数
    • 参数写完之后: NULL
    • 一般执行自己写的程序

    2. execv函数原型:

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

    分析:

    • path = /bin/ps
    • char* args[] = {"ps", "aux", NULL};
    • execv("/bin/ps", args);

    3. 执行PATH环境变量能够搜索到的程序

    int execlp(const char *file, const char *arg, ...);

    分析:

    • file: 执行的命令的名字
    • 第一arg:占位
    • 后边的arg: 命令的参数
    • 参数写完之后: NULL
    • 执行系统自带的程序
    • execlp执行自定义的程序: file参数绝对路径

    注意:如果file中包含/,则将其视为路径名,否者就按PATH环境变量,在它指定的各目录中搜可执行文件

    4. execvp函数原型:

    int execle(const char *path, const char *arg, ..., char *const envp[]);

    5. 执行指定路径, 指定环境变量下的程序

    int execle(const char *path, const char *arg, ..., char *const envp[]);

    分析:

    • path: 执行的程序的绝对路径  /home/itcast/a.out
    • arg: 执行的的程序的参数
    • envp: 用户自己指定的搜索目录, 替代PATH
    • char* env[] = {"/home/itcast", "/bin", NULL};

    6. execve函数原型:

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

    二、代码清单

    1. 测试代码:

     1 #include <unistd.h>
     2 #include <stdio.h>
     3 #include <stdlib.h>
     4  
     5 int main()
     6 {
     7     for(int i = 0; i < 8; ++i)
     8         printf(" parent i = %d
    ", i);
     9     pid_t pid = fork();
    10     if(pid == 0) 
    11     {
    12         execlp("ps", "ps", "aux", NULL);
    13         perror("execlp");
    14         exit(1);
    15     }
    16     for(int i = 0; i < 3; ++i)
    17         printf("----------- i = %d
    ", i);
    18     return 0;
    19 }

    输出结果:

    参考资料

  • 相关阅读:
    leetcode之String to Integer (atoi)
    初次思考
    leetcode之Reverse Words in a String
    Leetcode之Database篇
    在项目中添加类
    创建项目
    配置Eclipse

    递归
    多态
  • 原文地址:https://www.cnblogs.com/sunbines/p/10269190.html
Copyright © 2020-2023  润新知