从没有shell的C ++执行二进制文件

时间:2016-01-27 22:14:50

标签: c++

有没有办法在没有shell的情况下从我的C ++程序执行二进制文件?每当我使用system时,我的命令都会通过shell运行。

2 个答案:

答案 0 :(得分:6)

你需要:

  1. 分叉过程
  2. 调用子进程中的“exec”函数之一
  3. (如有必要)等待它停止
  4. 例如,该程序运行ls

    #include <iostream>
    
    #include <unistd.h>
    #include <sys/wait.h>
    
    // for example, let's "ls"
    int ls(const char *dir) {
       int pid, status;
       // first we fork the process
       if (pid = fork()) {
           // pid != 0: this is the parent process (i.e. our process)
           waitpid(pid, &status, 0); // wait for the child to exit
       } else {
           /* pid == 0: this is the child process. now let's load the
              "ls" program into this process and run it */
    
           const char executable[] = "/bin/ls";
    
           // load it. there are more exec__ functions, try 'man 3 exec'
           // execl takes the arguments as parameters. execv takes them as an array
           // this is execl though, so:
           //      exec         argv[0]  argv[1] end
           execl(executable, executable, dir,    NULL);
    
           /* exec does not return unless the program couldn't be started. 
              when the child process stops, the waitpid() above will return.
           */
    
    
       }
       return status; // this is the parent process again.
    }
    
    
    int main() {
    
       std::cout << "ls'ing /" << std::endl;
       std::cout << "returned: " << ls("/") << std::endl;
    
       return 0;
    }
    

    输出是:

    ls'ing /
    bin   dev  home        lib    lib64       media  opt   root  sbin     srv  tmp  var
    boot  etc  initrd.img  lib32  lost+found  mnt    proc  run   selinux  sys  usr  vmlinuz
    returned: 0
    

答案 1 :(得分:0)

我使用popen,fgets和pclose函数来执行外部命令行程序并重定向其输出。