Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute binary from C++ without shell

Tags:

c++

Is there a way to execute a binary from my C++ program without a shell? Whenever I use system my command gets run via a shell.

like image 261
Billy Avatar asked Dec 11 '22 18:12

Billy


1 Answers

You need to:

  1. fork the process
  2. call one of the "exec" functions in the child process
  3. (if necessary) wait for it to stop

For example, this program runs 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
like image 117
marinus Avatar answered Dec 30 '22 00:12

marinus