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

Bil*_*lly 0 c++

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

mar*_*nus 6

你需要:

  1. 分叉过程
  2. 在子进程中调用其中一个"exec"函数
  3. (如有必要)等待它停止

例如,该程序运行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;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

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
Run Code Online (Sandbox Code Playgroud)