zoukankan      html  css  js  c++  java
  • 使用exec函数族来进行多进程打开其他程序

    exec函数族

    int
      execl(const char *path, const char *arg0, ... /*, (char *)0 */);
    
    int
      execle(const char *path, const char *arg0, ...
             /*, (char *)0, char *const envp[] */);
    
    int
      execlp(const char *file, const char *arg0, ... /*, (char *)0 */);
    
    int
      execv(const char *path, char *const argv[]);
    
    int
      execvp(const char *file, char *const argv[]);
    
    int
      execvP(const char *file, const char *search_path, char *const argv[]);
    
    • execl, 可以指定路径进行运行自己的程序
    • execlp, 可以通过自己的环境变量,运行系统程序
    • execvp, 可以通过传入数组的方式

    execlp使用案例

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <pthread.h>
    
    int main(int agrc, char *argv[])
    {
      
      pid_t pid = fork();
      if (pid==-1){
        perror("fork error");
        exit(1);
      }else if(pid==0){ // 子进程
        // 找到NULL之后就结束
        // execlp("ls", "-l", "-d", "-h", NULL);  // 错误的写法
        execlp("ls", "ls",  "-l", "-d", "-h", NULL);  
        // 下面的代码只有在出错的时候才会执行
        perror("exec error");
        exit(1);
      }else if (pid>0){  // 父进程
        printf("I'm parent: %d
    ");
      }
      
      return 0;
      
    }
    

    execl的使用

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <pthread.h>
    
    int main(int agrc, char *argv[])
    {
      
      pid_t pid = fork();
      if (pid==-1){
        perror("fork error");
        exit(1);
      }else if(pid==0){ // 子进程
        // 找到NULL之后就结束
        // execlp("ls", "-l", "-d", "-h", NULL);  // 错误的写法
        //execlp("ls", "ls",  "-l", "-d", "-h", NULL);  
        execl("./a.out", "a.out",  "-l", "-d", "-h", NULL);  
        // 下面的代码只有在出错的时候才会执行
        perror("exec error");
        exit(1);
      }else if (pid>0){  // 父进程
        printf("I'm parent: %d
    ");
      }
      
      return 0;
      
    }
    

    exec函数族的一般规律

    • exec函数一旦调用成功,就执行新的程序,不返回。只有失败才返回,错误值为-1,通常直接在exec函数后直接调用perror()和exit(),不需要进行if判断
    • l(list) 命令行参数列表
    • p(path) 搜索file的时候使用的path变量
    • v(vector)使用命令行参数数组
    • e (environment) 使用环境变量数组,不使用进程原有的环境变量,设置新添加的环境变量
    • 其实只有execve 才是真正的系统调用,其他的exec函数族都是调用的execve
  • 相关阅读:
    改进神经网络及深度学习的学习方法
    caffe+win7+vs2013 仅CPU环境安装
    读书笔记--C陷阱与缺陷(七)
    读书笔记--C陷阱与缺陷(六)
    读书笔记--C陷阱与缺陷(五)
    读书笔记--C陷阱与缺陷(四)
    读书笔记--C陷阱与缺陷(三)
    搭建centos7的开发环境3-Spark安装配置
    Spark学习笔记
    Python2和Python3比较分析
  • 原文地址:https://www.cnblogs.com/fandx/p/12518339.html
Copyright © 2011-2022 走看看