6

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.

2
  • 5
    The usual way is fork() followed by exec(). See examples on the manpages. Commented Jan 27, 2016 at 22:17
  • Which is the same way every child is spawned. It's what the shell does. It's how every process except for init is started. Commented Jan 27, 2016 at 23:02

2 Answers 2

16

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
Sign up to request clarification or add additional context in comments.

Comments

-1

I used popen, fgets and pclose functions to execute external command line program and redirect its output.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.