简体   繁体   English

在没有外壳的情况下从C ++执行二进制文件

[英]Execute binary from C++ without shell

Is there a way to execute a binary from my C++ program without a shell? 有没有一种方法可以在没有外壳的情况下从我的C ++程序执行二进制文件? Whenever I use system my command gets run via a shell. 每当我使用system时,我的命令都会通过shell运行。

You need to: 你需要:

  1. fork the process 分叉过程
  2. call one of the "exec" functions in the child process 在子进程中调用“ exec”函数之一
  3. (if necessary) wait for it to stop (如有必要)等待其停止

For example, this program runs ls . 例如,此程序运行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;
}

And the output is: 输出为:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM