Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Another Program in Linux from a C++ Program

Tags:

Okay so my question is this. Say I have a simple C++ code:

#include <iostream> using namespace std;  int main(){    cout << "Hello World" << endl;    return 0; } 

Now say I have this program that I would like to run in my program, call it prog. Running this in the terminal could be done by:

./prog 

Is there a way to just do this from my simple C++ program? For instance

#include <iostream> using namespace std;  int main(){    ./prog ??    cout << "Hello World" << endl;    return 0; } 

Any feedback would be very much obliged.

like image 498
Vincent Russo Avatar asked Feb 02 '12 21:02

Vincent Russo


People also ask

Can C programs run on Linux?

In order to run a C program in Linux, you need to have a C compiler present on your systems. The most popular compiler is gcc (GNU Compiler Collection). Keep in mind that it is optional to provide the output object file (-o my_program).

Can a program run another program?

The common case is a "program" like Firefox -- software you run on your computer to solve a particular problem. A computer can run multiple programs at the same time and is responsible for keeping their memory separate.


2 Answers

You want the system() library call; see system(3). For example:

#include <cstdlib>  int main() {    std::system("./prog");    return 0; } 

The exact command string will be system-dependent, of course.

like image 121
J. C. Salomon Avatar answered Oct 18 '22 02:10

J. C. Salomon


You can also use popen

#include <stdio.h>  int main(void) {         FILE *handle = popen("./prog", "r");          if (handle == NULL) {                 return 1;         }          char buf[64];         size_t readn;         while ((readn = fread(buf, 1, sizeof(buf), handle)) > 0) {                 fwrite(buf, 1, readn, stdout);         }          pclose(handle);          return 0; } 
like image 28
xda1001 Avatar answered Oct 18 '22 01:10

xda1001