Execute binary from C++ without shell -
is there way execute binary c++ program without shell? whenever use system command gets run via shell.
you need to:
- fork process
- call 1 of "exec" functions in child process
- (if necessary) wait stop
for example, program runs ls.
#include <iostream> #include <unistd.h> #include <sys/wait.h> // example, let's "ls" int ls(const char *dir) { int pid, status; // first fork process if (pid = fork()) { // pid != 0: parent process (i.e. our process) waitpid(pid, &status, 0); // wait child exit } else { /* pid == 0: child process. let's load "ls" program process , run */ const char executable[] = "/bin/ls"; // load it. there more exec__ functions, try 'man 3 exec' // execl takes arguments parameters. execv takes them array // execl though, so: // exec argv[0] argv[1] end execl(executable, executable, dir, null); /* exec not return unless program couldn't started. when child process stops, waitpid() above return. */ } return status; // parent process again. } int main() { std::cout << "ls'ing /" << std::endl; std::cout << "returned: " << ls("/") << std::endl; return 0; } and 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
Comments
Post a Comment